Convert object string to JSON
Asked Answered
R

20

167

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.

Reputation answered 27/1, 2012 at 16:11 Comment(6)
Why is your string not valid JSON in the first place? How are you generating that?Misstate
The string is stored in a data-attrubute, like this: <div data-object="{hello:'world'}"></div> and I don't want to use single quotes in the HTML(so it is probably not to be trusted)Reputation
@snorpey: <div data-object='{"hello":"world"}'></div> is 100% valid HTML (what does single quotes have to do with trusting it or not?). If you do it this way, you can just JSON.parse it and it'll work fine. Note: the keys need to be quoted too.Misstate
@Rocket thanks for your efforts! I just wanted to find a way around having to use single quotes in HTML (even though it is 100% valid) and JSON notation.Reputation
@snorpey: They way around is not to put JSON in a HTML attribute in the first place. I guess you could use double quotes, and escape the ones in the JSON <div data-object="{\"hello\":\"world\"}"></div>. If you don't want to use valid JSON in the attribute, then you're gonna have to make your own format and parse it yourself.Misstate
These are just tips instead of answer. - You can use http://www.jsoneditoronline.org/ to verify my JSON. - While passing JSON string from code behind mindful of adding appropriate escape characters.Roadstead
T
184

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).

Torchwood answered 27/1, 2012 at 16:20 Comment(6)
this does not make sense, if string is from trusted source, why we convert it instead we make it as valid json.Selfaddressed
@Selfaddressed The idea is to convert from invalid JSON to valid JSON, so eval converts the string to a JavaScript object (which works, as long as the string represents valid JavaScript, even if it's not valid JSON). Then JSON.stringify converts from an object back to a (valid) JSON string. Calling eval is dangerous if the string is not from a trusted source because it could literally run any JavaScript which opens up the possibility of cross-site scripting attacks.Torchwood
eval will still do bad things in this case if the string is constructed, for example, like this: var str = "(function() {console.log(\"bad\")})()";Seaport
Using eval() will execute JS code. It can be easily abused.Anglim
@allenhwkim: we never trust any source. Trust in IT means check, check and check again.Walford
SyntaxError: Unexpected token {Shiny
M
112

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);
Misstate answered 27/1, 2012 at 16:19 Comment(0)
H
50

jQuery.parseJSON

str = jQuery.parseJSON(str)

Edit. This is provided you have a valid JSON string

Helsie answered 27/1, 2012 at 16:15 Comment(1)
true I saw the question as how to convert JSON string to objectHelsie
A
43

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);
Autogenesis answered 15/12, 2013 at 23:24 Comment(3)
Converting jsontext to a String object via new String(jsontext) is probably even better, for type safety.Uterine
@fuzzyanalysis: No, primitive wrappers should never be used.Moulding
JSON.parse() should be the accepted answer here as stated by @LouiseMcMahonBitten
S
29

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…}
Selfaddressed answered 10/10, 2014 at 3:9 Comment(4)
We're trying to de-evalify b using JSON.parse our code and this looks like a good solution. We're still going to have to handle constant replacement by hand, but at least this allows to contain those cases.Feliciafeliciano
It's almost perfect. Does not work when : is in one of values.Enchant
eval is pure evil, I think this is the way to goBullyboy
absolute geinusCopartner
T
9

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) );
Thatch answered 27/1, 2012 at 16:18 Comment(18)
To the anonymous down-voter. I challenge you to provide a better solution. Apart from that a reason for the down-vote would be nice.Thatch
Why was this down-voted? Yes, eval is bad, but his string is not valid JSON, so he can't use JSON.parse.Misstate
@Rocket: You are wrong. a) eval() is the only way to do it. b) I cautioned the OP about it. c) Look at Matthew Crumley's answer and think of a better explanation. (Oh, and d) the statement eval() is bad is nonsense in this generalized form.)Thatch
I'm wrong for agreeing with you? That comment was asking why this was-voted. I was explaining why eval has to be used here. Did you see my answer?Misstate
@Rocket: Ah, misunderstanding right there. Sorry, I thought the down-vote was yours. :)Thatch
@Thatch I've down-voted you. You're right that eval() is the only way, but your solution doesn't work – you forget add round brackets. See my post, or post from @Matthew CrumleyFathead
@kuboslav: It works fine, did you even test it? He's doing eval("var x = " + str + ";") which is totally valid JS. You don't need to do var x = ({a:12}).Misstate
@Rocket Yes, I've tested it – it doesn't work. See my post before answer.Fathead
@kuboslav: Then you're testing it wrong, because it works fine. jsfiddle.net/ExHWkMisstate
@Rocket – Again: 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 objectFathead
@kuboslav: Again: He's not evaling an object literal. He's evaling a line of code that sets a variable to an object. I'll ask you again, Did you test it? It works just fine: jsfiddle.net/ExHWkMisstate
@Fathead I usually test things before I post them here. Still there might be errors in them or they might not work everywhere. I'd appreciate a comment if that's the case. An uncommented downvote is not helpful at all - not for me and not for anybody else who might wonder. (Apart from that, I'm not into down-voting. I leave just a comment even under dead-wrong answers. But maybe that's just me.)Thatch
@Thatch I'm sorry, but I write slowly on notebook keyboard. In future I'll first write comment and then would down-vote. I've down-voted because it doesn't work in my IE7.Fathead
@Fathead It does not work in IE7 because IE7 does not have native JSON support. It will start to work as soon as you use json2.js. Don't be so trigger-happy.Thatch
@kuboslav: Why are you still using IE7, it's 2012, get with the times :-P (P.S. It doesn't work in IE7 because it doesn't have native JSON, nothing to do with the eval. You can use Crockford's JSON shim to add JSON support to IE7.)Misstate
@Thatch you can utilize the onclick attribute of a dummy element to accomplish the same thing, so eval() isn't the only way (technically speaking). I left an answer to show how this alternative method works in practice.Microbiology
@csu Isn't that method using eval() as well, under the hood? I would not be surprised.Thatch
@Thatch if we want to be uber technical, eval() is a call for the JS engine to parse and run script content, and every textual bit of code (onclick, etc) or script tag invokes the same basic mechanism that backs eval(). The one benefit textual script tags, attributes, and new Function creation can provide, is they are generally easier to optimize (once cast, and cached) for reuse. Constantly using eval to reevaluate the same textual code strings is much harder to optimize in the same way. As the OP asked for no explicit use of eval(), I felt the solution I provided fit the bill.Microbiology
R
4

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.

Rabbit answered 27/1, 2012 at 16:19 Comment(1)
It should be JSON.stringify(eval('('+str+')'));, not that I condone eval, but his string isn't valid JSON so JSON.parse doesn't work.Misstate
A
4

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"
}
Atwell answered 19/8, 2013 at 6:7 Comment(0)
D
3

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

Dayak answered 2/2, 2018 at 10:24 Comment(0)
C
3

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>
Chamonix answered 2/2, 2018 at 10:39 Comment(0)
S
3

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

Snag answered 5/6, 2019 at 9:56 Comment(0)
P
2

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

Phelps answered 27/1, 2012 at 16:15 Comment(1)
This doesn't really help, as the string isn't valid JSON.Misstate
M
2

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)

Microbiology answered 28/9, 2013 at 16:7 Comment(0)
F
1

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'] })");
Fathead answered 27/1, 2012 at 16:26 Comment(0)
G
0

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\"] }"
Gyasi answered 27/1, 2018 at 12:57 Comment(0)
M
0

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>
Maleficent answered 27/1, 2018 at 22:46 Comment(0)
I
0

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.

Iroquois answered 1/2, 2018 at 17:42 Comment(0)
M
0

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".

Mighty answered 2/2, 2018 at 5:49 Comment(0)
A
0
var str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }";
var json = JSON.stringify(eval("(" + str + ")"));
Annuitant answered 2/2, 2018 at 11:17 Comment(0)
I
-1

Maybe you have to try this:

str = jQuery.parseJSON(str)
Intromission answered 2/2, 2018 at 7:18 Comment(1)
Question specified "or jQuery" and this is the perfect solution if you have it available.Beaty

© 2022 - 2024 — McMap. All rights reserved.