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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5216205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:12:27  来源:igfitidea点击:

how to manipulate json objects in javascripts/jquery?

javascriptjqueryjson

提问by Amit

I wanted to add delete update elements in json using jquery/javascript and when the file submit is done to the server wanted to consider the latest json object.

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

Can you suggest and approach i am stuck.

你能建议并接近我吗?

回答by Soth

I use JSON.parse and JSON.stringify to manipulate.

我使用 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

EDIT: Fixed some typos: JSFiddle

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

回答by Trafalmadorian

As mentioned, you can use jQuery's json functions to edit the object. Let me demonstrate how you might do this, with a little code:

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

let's take this JSON object:

让我们以这个 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"
}

Now, let's say your server is storing that as a flat JSON file somewhere...what we'd do is load it on the client with jQuery's ajax methods, and edit it using a callback. After manipulating the object, we'll (for demonstration purposes) immediately send it back to a server-side script, which will presumably overwrite the current flat file:

现在,假设您的服务器将其作为平面 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");
    });
});

Hope that helps in understanding the pattern involved!

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

回答by rahulmohan

JSON data can be directly manipulated in javascript after parsing. (See Brad's comment on your question). To send the updated data back to server you can use $.post. Now, doesn't this solve your problem? If not, then please explain your problem in more detail.

JSON数据解析后可以直接在javascript中进行操作。(请参阅布拉德对您的问题的评论)。要将更新的数据发送回服务器,您可以使用 $.post。现在,这不能解决您的问题吗?如果不是,那么请更详细地解释您的问题。