2

I am trying to parse a string into an object. I have looked at the jQueryparseJSON documentation at the following link I've also included the jquery library so I know it's not that.

This is my code so far

var str = "{'val1': 1, 'val2': 2, 'val3': 3}";
var obj = jQueryparseJSON( str );
alert(obj.val1);

In Firebug I am getting the following errors:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I know the solution is more than likely very simple, but I have been repeatedly overlooking it.

Anri
  • 1,706
  • 2
  • 17
  • 36
beckah
  • 1,543
  • 6
  • 28
  • 61
  • Have a look at http://stackoverflow.com/questions/24592841/is-there-any-difference-in-json-key-when-using-single-quote-and-double-quote – Musa Jul 14 '14 at 16:59

4 Answers4

6

The test string in your sample code is not valid JSON:

var str = '{"val1": 1, "val2": 2, "val3": 3}';
var obj = jQuery.parseJSON( str );
alert(obj.val1);

Now, if you're doing all this because some service is making that object available as a JSON string, it's probably the case that jQuery will do the parsing step for you anyway. If you're just trying to include an object literal into your JavaScript code, then there's no reason to involve the JSON services at all:

var obj = { val1: 1, val2: 2, val3: 3 };

creates an object.

Note that JSON syntax is stricter than JavaScript object literal syntax. JSON insists that property names be quoted with double-quote characters, and of course values can only be numbers, strings, booleans, or null.

Pointy
  • 405,095
  • 59
  • 585
  • 614
3

Your string is not valid JSON. Object keys must be surrounded with double quotes, not single quotes.

var str = '{"val1": 1, "val2": 2, "val3": 3}';
var obj = jQuery.parseJSON(str);
alert(obj.val1);

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
0
function str2json (str, val, obj) {
var obj = str.indexOf("'") != -1 
          ? JSON.parse(str.replace(/'/g, "\"")) 
          : JSON.parse(str);
    return (val === undefined ? obj /* JSON.stringify(obj) */ : obj[val])
};

str2json("{'val1': 1, 'val2': 2, 'val3': 3}", "val1"); // `1`

str2json("{'val1': 1, 'val2': 2, 'val3': 3}") 
// `obj` : `[object Object]` ,
// `JSON.stringify(obj)` : `{"val1":1,"val2":2,"val3":3}`

jsfiddle http://jsfiddle.net/guest271314/n8jLG/

guest271314
  • 1
  • 15
  • 104
  • 177
  • This is going to cause problems when there are single quotes embedded within string values or in the keys themselves. – cookie monster Jul 14 '14 at 18:49
  • @cookiemonster Ok, good point. Should answer be withdrawn ? Or, try to fix by assessing quotes more thoroughly ? Where case `str`, or `var`, is actual string appearing as `arguments[0]` above ? Havnt viewed a `key` which included single quotes; example in the wild ? Thanks – guest271314 Jul 14 '14 at 19:23
0

You have a typo error in your code :

here var obj = jQueryparseJSON( str );

should be var obj = jQuery.parseJSON( str );

Jimmy Obonyo Abor
  • 7,335
  • 10
  • 43
  • 71