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?
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?
Share Improve this question asked Jan 5, 2012 at 21:34 jcveganjcvegan 3,1709 gold badges45 silver badges67 bronze badges 1- I realized that is a string, I had to use JSON.Parse to get the JSON object – jcvegan Commented Jan 5, 2012 at 21:40
5 Answers
Reset to default 6To go from a JSON string to a JavaScript object: JSON.parse
, or $.parseJSON
if you're using jQuery and concerned about patibility 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);
var parsed = JSON.parse('{"a": 1}');
parsed.b = 2;
var string = JSON.stringify(parsed);
//string is: '{"a":1,"b":2}'
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);
As JSON is an JavaScript object you can simply manipulate it with JavaScript.
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.