2

I know that json.stringify() function converts a json object to json string.

json.stringify({x:9})

this will return string "{"x" : 9}"

But is there a way to convert a simple string into json format? For example i want this

var str = '{x: 9}'
json.stringify(str)  //"{"x" : 9}"
1
  • 1
    var str = '{"x": 9}'; var obj= JSON.parse(str) Commented Mar 29, 2016 at 9:37

3 Answers 3

3

With a proper format of string, you can use JSON.parse.

var str = '{"x" : 9}',
    obj = JSON.parse(str);

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');            

Sign up to request clarification or add additional context in comments.

Comments

0

If you are using jQuery then you can use $.parseJSON See http://api.jquery.com/jquery.parsejson/

Can also visit Parse JSON in JavaScript?

Comments

0

First solution using eval:

const parseRelaxedJSON = (str) => eval('(_ => (' + str + '))()')
JSON.stringify(parseRelaxedJSON('{x: 5}'))

(_ => (' + str + '))() is a self-executing anonymous function. It is necessary for eval to evaluate strings similar to {x: 5}. This way eval will be evaluating the expression function (_ => ({x: 5}))() which if you're not familiar with ES6 syntax is equivalent to:

(function() {
  return {x: 5}
})()

Second solution: using a proper 'relaxed' JSON parser like JSON5

JSON.stringify(JSON5.parse('{x: 2}'))

JSBin

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.