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}"
Maira Muneer
  • 75
  • 1
  • 1
  • 7

3 Answers3

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>');            
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
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?

Community
  • 1
  • 1
Ashwin Hegde
  • 1,733
  • 4
  • 19
  • 49
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

homam
  • 1,945
  • 1
  • 19
  • 26