Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to manipulate json objects in javascripts/jquery? [closed]

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.

Can you suggest and approach i am stuck.

like image 284
Amit Avatar asked Mar 07 '11 05:03

Amit


People also ask

What is toJSON () in JSON?

toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.

What does JSON Stringify () method do?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

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

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

like image 183
Soth Avatar answered Oct 06 '22 01:10

Soth


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:

let's 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"
}

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:

$.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!

like image 21
Trafalmadorian Avatar answered Oct 06 '22 01:10

Trafalmadorian