How to manipulate json objects in javascripts / jquery?

I wanted to add delete delete elements to json using jquery / javascript, and when the file is sent to the server, it wants to consider the last json object.

Can you suggest and come up, I'm stuck.

+5
source share
3 answers

I use JSON.parse and JSON.stringify for control.

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

+9
source

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

take this JSON object:

{
 "people":[
     {"name":"Bob","score":9},
     {"name":"Joe","score":6},
     {"name":"Tom","score":7}
  ],
 "projects":[
     {"id":2347,"entries":5},
     {"id":8563,"entries":3}
  ],
 "lastUser":"Bob"
}

, JSON -... , jQuery ajax- . ( ) script, :

$.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");
    });
});

, !

+4

JSON javascript . (. ). , $.post. , ? , , , .

0

All Articles