如何在javascripts/jquery中操作json对象?

Ami*_*mit 5 javascript jquery json

我想使用jquery/javascript在json中添加删除更新元素,并且当向服务器提交文件时想要考虑最新的json对象.

你能建议和接近我被卡住了吗?

Sot*_*oth 10

我使用JSON.parse和JSON.stringify进行操作.

json_flat = '{"page":"1","total":"2","ids":[{"id":"3085"},{"id":"3086"}]}'; // your flat json    
json_object = JSON.parse(json_flat); //convert to an object

//Manipulation
json_object.page = "6"; //change values
delete json_object.total; //delete a value

json_flat = JSON.stringify(json_object); //convert back to flat
Run Code Online (Sandbox Code Playgroud)

编辑:修正了一些错别字:JSFiddle


Tra*_*ian 5

如前所述,您可以使用 jQuery 的 json 函数来编辑对象。让我用一些代码来演示你如何做到这一点:

让我们以这个 JSON 对象为例:

{
 "people":[
     {"name":"Bob","score":9},
     {"name":"Joe","score":6},
     {"name":"Tom","score":7}
  ],
 "projects":[
     {"id":2347,"entries":5},
     {"id":8563,"entries":3}
  ],
 "lastUser":"Bob"
}
Run Code Online (Sandbox Code Playgroud)

现在,假设您的服务器将其作为平面 JSON 文件存储在某处……我们要做的是使用 jQuery 的 ajax 方法将其加载到客户端,并使用回调对其进行编辑。操作对象后,我们将(出于演示目的)立即将其发送回服务器端脚本,这可能会覆盖当前的平面文件:

$.getJSON(/*path to JSON file here*/,function(response){
    response.lastUser="Tom"; //This is where the sample manipulation occurs.
    $.post(/* path to server-side script*/,response,function(){
      alert("Object Saved");
    });
});
Run Code Online (Sandbox Code Playgroud)

希望有助于理解所涉及的模式!

  • 操作在 `response.lastUser="Tom"; 行中演示。`. 直接修改JSON对象然后发回:) (2认同)