javascript - Jquery 和 JSON : Replace section of JSON array

标签 javascript jquery json replace

我已经阅读了大量相关内容,但似乎找不到适合我的解决方案。我正在构建一个拖放菜单系统并将结构作为 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/

相关文章:

javascript - 我无法编辑 Selenium Standalone 上的超时

javascript - 创建一个函数,无论调用多少次,都仅在第一个异步调用完成时运行?

javascript - 如何在 if 语句中使用多个元素、多个事件但相同的函数

python - Pyral+新建任务+ValueError : No JSON object could be decoded

javascript - JSON-如何从json字符串中获取单个内容

javascript - 什么?和 ?? javascript中的运算符呢?

javascript - KnockoutJS 选项与重复值绑定(bind)

javascript - jQuery:单击按钮时添加到 html 字符串

jquery - 如何使用 InvokeScript() 从 .NET WebBrowser 控件调用 jQuery 函数?

php - 是否可以将完整记录(整行)连接到 MySQL 中的一列中?如何?