Reputation: 3170
I have some web services that receive JSON data send by jquery method. But I need to edit the object before send this data. Is there any way to parse a JSON object to a simple object in javascript, modify it and then parse it again to JSON. or maybe update this JSON object without parse it?
Upvotes: 3
Views: 2791
Reputation: 359786
To go from a JSON string to a JavaScript object: JSON.parse
, or $.parseJSON
if you're using jQuery and concerned about compatibility with older browsers.
To go from a JavaScript object to a JSON string: JSON.stringify
.
If I've already do this var myData = JSON.stringify({ oJson:{data1 :1}}); and then I want to update that information setting data1 = 2, what is the best way to do this?
var myData = JSON.stringify({ oJson:{data1 :1}});
// later...
parsedData = JSON.parse(myData);
parsedData.oJson.data1 = 2;
myData = JSON.stringify(parsedData);
Even better though, if you save a reference to the object before stringifying it, you don't have to parse the JSON at all:
var obj = { oJson:{data1 :1}};
var myData = JSON.stringify(obj);
// later...
obj.oJson.data1 = 2;
myData = JSON.stringify(obj);
Upvotes: 6
Reputation: 1576
You could do something like this to get a javascript object:
var jsObject = JSON.parse(jsonString);
Then you could modify jsObject
and turn it back into a JSON string with JSON.stringify
.
This page has more information on it.
Upvotes: 0
Reputation: 110892
As JSON is an JavaScript object you can simply manipulate it with JavaScript.
Upvotes: 0
Reputation: 48415
I think something like the following should work...
//Convert your JSON object into a JavaScript object
var myObject = JSON.parse(json);
//You can then manipulate the JavaScript object like any other
myObject.SomeValue = "new";
//Then you can convert back to a JSON formatted string
json = JSON.stringify(myObject);
Upvotes: 0
Reputation: 340713
var parsed = JSON.parse('{"a": 1}');
parsed.b = 2;
var string = JSON.stringify(parsed);
//string is: '{"a":1,"b":2}'
Upvotes: 3