Convert object string to JSON

JavascriptJsonObject

Javascript Problem Overview


How can I convert a string that describes an object into a JSON string using JavaScript (or jQuery)?

e.g: Convert this (NOT a valid JSON string):

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"

into this:

str = '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'

I would love to avoid using eval() if possible.

Javascript Solutions


Solution 1 - Javascript

If the string is from a trusted source, you could use eval then JSON.stringify the result. Like this:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

Note that when you eval an object literal, it has to be wrapped in parentheses, otherwise the braces are parsed as a block instead of an object.

I also agree with the comments under the question that it would be much better to just encode the object in valid JSON to begin with and avoid having to parse, encode, then presumably parse it again. HTML supports single-quoted attributes (just be sure to HTML-encode any single quotes inside strings).

Solution 2 - Javascript

Your string is not valid JSON, so JSON.parse (or jQuery's $.parseJSON) won't work.

One way would be to use eval to "parse" the "invalid" JSON, and then stringify it to "convert" it to valid JSON.

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
str = JSON.stringify(eval('('+str+')'));

I suggest instead of trying to "fix" your invalid JSON, you start with valid JSON in the first place. How is str being generated, it should be fixed there, before it's generated, not after.

EDIT: You said (in the comments) this string is stored in a data attribute:

<div data-object="{hello:'world'}"></div>

I suggest you fix it here, so it can just be JSON.parsed. First, both they keys and values need to be quoted in double quotes. It should look like (single quoted attributes in HTML are valid):

<div data-object='{"hello":"world"}'></div>

Now, you can just use JSON.parse (or jQuery's $.parseJSON).

var str = '{"hello":"world"}';
var obj = JSON.parse(str);

Solution 3 - Javascript

jQuery.parseJSON

str = jQuery.parseJSON(str)

Edit. This is provided you have a valid JSON string

Solution 4 - Javascript

Use simple code in the link below :

http://msdn.microsoft.com/es-es/library/ie/cc836466%28v=vs.94%29.aspx

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);

and reverse

var str = JSON.stringify(arr);

Solution 5 - Javascript

I hope this little function converts invalid JSON string to valid one.

function JSONize(str) {
  return str
    // wrap keys without quote with valid double quote
    .replace(/([\$\w]+)\s*:/g, function(_, $1){return '"'+$1+'":'})    
    // replacing single quote wrapped ones to double quote 
    .replace(/'([^']+)'/g, function(_, $1){return '"'+$1+'"'})         
}

Result

let invalidJSON = "{ hello: 'world',foo:1,  bar  : '2', foo1: 1, _bar : 2, $2: 3, 'xxx': 5, \"fuz\": 4, places: ['Africa', 'America', 'Asia', 'Australia'] }"
JSON.parse(invalidJSON) 
//Result: Uncaught SyntaxError: Unexpected token h VM1058:2
JSON.parse(JSONize(invalidJSON)) 
//Result: Object {hello: "world", foo: 1, bar: "2", foo1: 1, _bar: 2…}

Solution 6 - Javascript

Use with caution (because of eval()):

function strToJson(str) {
  eval("var x = " + str + ";");
  return JSON.stringify(x);
}

call as:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
alert( strToJson(str) );

Solution 7 - Javascript

Disclaimer: don't try this at home, or for anything that requires other devs taking you seriously:

JSON.stringify(eval('(' + str + ')'));

There, I did it.
Try not to do it tho, eval is BAD for you. As told above, use Crockford's JSON shim for older browsers (IE7 and under)

This method requires your string to be valid javascript, which will be converted to a javascript object that can then be serialized to JSON.

edit: fixed as Rocket suggested.

Solution 8 - Javascript

I put my answer for someone who are interested in this old thread.

I created the HTML5 data-* parser for jQuery plugin and demo which convert a malformed JSON string into a JavaScript object without using eval().

It can pass the HTML5 data-* attributes bellow:

<div data-object='{"hello":"world"}'></div>
<div data-object="{hello:'world'}"></div>
<div data-object="hello:world"></div>

into the object:

{
    hello: "world"
}

Solution 9 - Javascript

You need to use "eval" then JSON.stringify then JSON.parse to the result.

 var errorString= "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
 var jsonValidString = JSON.stringify(eval("(" + errorString+ ")"));
 var JSONObj=JSON.parse(jsonValidString);

enter image description here

Solution 10 - Javascript

Douglas Crockford has a converter, but I'm not sure it will help with bad JSON to good JSON.

https://github.com/douglascrockford/JSON-js

Solution 11 - Javascript

There's a much simpler way to accomplish this feat, just hijack the onclick attribute of a dummy element to force a return of your string as a JavaScript object:

var jsonify = (function(div){
  return function(json){
    div.setAttribute('onclick', 'this.__json__ = ' + json);
    div.click();
    return div.__json__;
  }
})(document.createElement('div'));

// Let's say you had a string like '{ one: 1 }' (malformed, a key without quotes)
// jsonify('{ one: 1 }') will output a good ol' JS object ;)

Here's a demo: http://codepen.io/csuwldcat/pen/dfzsu (open your console)

Solution 12 - Javascript

You have to write round brackets, because without them eval will consider code inside curly brackets as block of commands.

var i = eval("({ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] })");

Solution 13 - Javascript

Your best and safest bet would be JSON5 – JSON for Humans. It is created specifically for that use case.

const result = JSON5.parse("{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }");

console.log(JSON.stringify(result));

<script src="https://cdnjs.cloudflare.com/ajax/libs/json5/0.5.1/json5.min.js"></script>

Solution 14 - Javascript

Using new Function() is better than eval, but still should only be used with safe input.

const parseJSON = obj => Function('"use strict";return (' + obj + ')')();

console.log(parseJSON("{a:(4-1), b:function(){}, c:new Date()}"))
// outputs: Object { a: 3, b: b(), c: Date 2019-06-05T09:55:11.777Z }

Sources: MDN, 2ality

Solution 15 - Javascript

For your simple example above, you can do this using 2 simple regex replaces:

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
str.replace(/(\w+):/g, '"$1":').replace(/'/g, '"');
 => '{ "hello": "world", "places": ["Africa", "America", "Asia", "Australia"] }'

Big caveat: This naive approach assumes that the object has no strings containing a ' or : character. For example, I can't think of a good way to convert the following object-string to JSON without using eval:

"{ hello: 'world', places: [\"America: The Progressive's Nightmare\"] }"

Solution 16 - Javascript

Just for the quirks of it, you can convert your string via babel-standalone

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";

function toJSON() {
  return {
    visitor: {
      Identifier(path) {
        path.node.name = '"' + path.node.name + '"'
      },
      StringLiteral(path) {
        delete path.node.extra
      }
    }
  }
}
Babel.registerPlugin('toJSON', toJSON);
var parsed = Babel.transform('(' + str + ')', {
  plugins: ['toJSON']
});
var json = parsed.code.slice(1, -2)
console.log(JSON.parse(json))

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

Solution 17 - Javascript

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" var fStr = str .replace(/([A-z]*)(:)/g, '"$1":') .replace(/'/g, """)

console.log(JSON.parse(fStr))enter image description here

Sorry I am on my phone, here is a pic.

Solution 18 - Javascript

A solution with one regex and not using eval:

str.replace(/([\s\S]*?)(')(.+?)(')([\s\S]*?)/g, "$1\"$3\"$5")

This I believe should work for multiple lines and all possible occurrences (/g flag) of single-quote 'string' replaced with double-quote "string".

Solution 19 - Javascript

var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));

Solution 20 - Javascript

This will also work

let str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
let json = JSON.stringify(eval("("+ str +")"));

Solution 21 - Javascript

Maybe you have to try this:

str = jQuery.parseJSON(str)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsnorpeyView Question on Stackoverflow
Solution 1 - JavascriptMatthew CrumleyView Answer on Stackoverflow
Solution 2 - JavascriptRocket HazmatView Answer on Stackoverflow
Solution 3 - JavascriptFarmorView Answer on Stackoverflow
Solution 4 - JavascriptRonald CoariteView Answer on Stackoverflow
Solution 5 - JavascriptallenhwkimView Answer on Stackoverflow
Solution 6 - JavascriptTomalakView Answer on Stackoverflow
Solution 7 - JavascriptgonchukiView Answer on Stackoverflow
Solution 8 - JavascripttokkonopapaView Answer on Stackoverflow
Solution 9 - JavascriptNegi RoxView Answer on Stackoverflow
Solution 10 - JavascriptSethView Answer on Stackoverflow
Solution 11 - JavascriptcsuwldcatView Answer on Stackoverflow
Solution 12 - JavascriptkuboslavView Answer on Stackoverflow
Solution 13 - JavascriptdereliView Answer on Stackoverflow
Solution 14 - JavascriptSamGoodyView Answer on Stackoverflow
Solution 15 - JavascriptTopher HuntView Answer on Stackoverflow
Solution 16 - JavascriptMoritz RoesslerView Answer on Stackoverflow
Solution 17 - JavascriptFrancis LeighView Answer on Stackoverflow
Solution 18 - JavascriptChaitanya PView Answer on Stackoverflow
Solution 19 - JavascriptpraveenkumarView Answer on Stackoverflow
Solution 20 - JavascriptAYKView Answer on Stackoverflow
Solution 21 - JavascriptJay Hyber CarocoyView Answer on Stackoverflow