JQuery.parseJSON not working with string

前端 未结 4 1017
野的像风
野的像风 2020-12-16 08:54

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

相关标签:
4条回答
  • 2020-12-16 09:17

    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.

    0 讨论(0)
  • 2020-12-16 09:26
    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/

    0 讨论(0)
  • 2020-12-16 09:28

    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

    0 讨论(0)
  • 2020-12-16 09:34

    You have a typo error in your code :

    here var obj = jQueryparseJSON( str );

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

    0 讨论(0)
提交回复
热议问题