我已经阅读了大量相关内容,但似乎找不到适合我的解决方案。我正在构建一个拖放菜单系统并将结构作为 JSON 保存到数据库中。
我有一个隐藏字段作为提交到数据库的表单的一部分。该隐藏字段包含完整的 JSON 字符串。
当我更新特定节点/菜单项时,我想搜索隐藏文本字段的值,找到我想要更新的 JSON 的“部分”并将其替换为新值。
对此最好的解决方案是什么?格雷普?替换为?
JSON 之前和之后的示例
// This is the full json string
[{"title":"Cool link","link":"link","cssclass":"","cssid":"","id":"1399209929525"},{"title":"New link","link":"new-link.html","cssclass":"","cssid":"","id":"1399209790202"},{"title":"Another link","link":"cool","cssclass":"","cssid":"","id":"1399209834496"}]
// This is the updated section
[{"title":"Another link changed","link":"cool","cssclass":"","cssid":"","id":"1399209834496"}]
因此,我有更新的部分,其中包含可供搜索的唯一 ID。
一个简单的解决方案是这样的,但它并不是这样工作的。
var currentsection = /'{"title":"' + edittitle + '","link":"' + editurl + '","cssclass":"' + editcssclass + '","cssid":"' + editcssid + '","id":"' + editid + '"}'/;
var newsection = /'{"title":"' + updatedtitle + '","link":"' + updatedlink + '","cssclass":"' + updatedcssclass + '","cssid":"' + updatedcssid + '","id":"' + updatedid + '"}'/;
$("#menu_items").val().find(currentsection).replaceWith(newsection);
您认为最好的方法是什么?非常感谢您抽出时间来提供帮助。我真的很感激。
最佳答案
我认为您应该创建 JSON 对象并使用它。通过这种方式,可以很容易地更改值并根据需要保存它;)
例如:
var json = YOUR JSON HERE;
var obj = JSON.parse(json);
// now you can update values as you want
// for example with example title
obj[0].title = "updatetitle";
然后,在发送 JSON 之前,您可能需要将其转换为纯文本
var json = JSON.stringify(obj);
关于javascript - Jquery 和 JSON : Replace section of JSON array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23471018/