If I have a string variable with the following value:
var myString = "{'nombre':'juan'}";
How can I convert a string to a JSON object in JavaScript?
If I have a string variable with the following value:
var myString = "{'nombre':'juan'}";
How can I convert a string to a JSON object in JavaScript?
Assuming we got the JSON syntax right, your string:
It's already JSON! , you don't need any conversion.
JSON notation is a way to serialize a JavaScript object into a string, so you already have JSON.
Now if you want to convert it to a JavaScript object.
and return it to JSON:
Finally, as @ratlab mentions, if your browser does not support the object,
JSON
you can use a library like json2.js or JSON 3Or use this polyfill from MDN directly in your code:
In JavaScript there are 2 methods to convert from string with JSON notation to object and vice
JSON.parse
versaJSON.stringify
:You should keep in mind that
null
,true
,false
are also valid JSON values and that character strings must include a double quote at the beginning and end of the string to be considered as such, otherwise they will be interpreted as other data types. Regular expressions and functions are not as JSON is a data exchange format and the latter are considered "code".You can find the full specification of the format here and also on the json.org page itself.
These features are supported in most browsers Chrome, Firefox 3.5+, Internet Explorer 8+, Opera 10.5+ and Safari 4.0+.
If it is not present, you can use the JSON2 library made by Douglas Crockford himself , the creator of this format, based on existing JavaScript structures.
Taking into account your initialization code:
Solution
Use of language intrinsic tools: JSON.parse()
The MDN documentation tells us that:
Using the word "JSON object" and "JSON text" may be a pleonasm but in reality it is so common that when it is expressed in that way it gives a whole context to the recipient of the message other than just using JSON.
This can be seen on the page: JSON in JavaScript .
Add to @dabbbb's answer.
which browsers like:
they have native support for JSON, in case you need to do this in older browsers you will need to include JSON2