JQuery.parseJSON not working with string

42,844

Solution 1

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.

Solution 2

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

Share:
42,844
beckah
Author by

beckah

Updated on December 31, 2020

Comments

  • beckah
    beckah over 3 years

    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.