解析有效JSON

时间:2017-04-17 03:42:37

标签: javascript json

我正在尝试解析一些JSON,但似乎我的控制字符很糟糕,即使http://jsonlint.com表示它有效。我需要改变什么才能真正有效?

{"panes": [{"col": {"3": 1}, "row": {"3": 1}, "width": 1, "widgets": [{"type": "Slider", "settings": {"max": 100, "min": 0, "step": 1, "color": "grey", "onSlide": "// Example: Convert temp from C to F and truncate to 2 decimal places.\n// return (datasources[\"MyDatasource\"].sensor.tempInF * 1.8 + 32).toFixed(2);\n\n", "showvalue": 1, "initialvalue": "0"}}], "col_width": 1}], "columns": null, "plugins": [], "version": 1, "allow_edit": true, "datasources": []}

这是JSONLint的输出形式,表示其有效JSON。当尝试使用JSON.parse()解析它时,我得到了以下错误:

SyntaxError: JSON.parse: bad control character in string literal at line 1 column 235 of the JSON data

{
    "panes": [{
        "col": {
            "3": 1
        },
        "row": {
            "3": 1
        },
        "width": 1,
        "widgets": [{
            "type": "Slider",
            "settings": {
                "max": 100,
                "min": 0,
                "step": 1,
                "color": "grey",
                "onSlide": "// Example: Convert temp from C to F and truncate to 2 decimal places.\n// return (datasources[\"MyDatasource\"].sensor.tempInF * 1.8 + 32).toFixed(2);\n\n",
                "showvalue": 1,
                "initialvalue": "0"
            }
        }],
        "col_width": 1
    }],
    "columns": null,
    "plugins": [],
    "version": 1,
    "allow_edit": true,
    "datasources": []
}

我试图解析一个php对象属性。

var js_object = JSON.parse('<?= php_object->json ?>');

1 个答案:

答案 0 :(得分:1)

您无需解析数据,您可以使用Javascript dot[brackets]表示法直接访问数据和每个对象

&#13;
&#13;
var data = {
    "panes": [{
        "col": {
            "3": 1
        },
        "row": {
            "3": 1
        },
        "width": 1,
        "widgets": [{
            "type": "Slider",
            "settings": {
                "max": 100,
                "min": 0,
                "step": 1,
                "color": "grey",
                "onSlide": "// Example: Convert temp from C to F and truncate to 2 decimal places.\n// return (datasources[\"MyDatasource\"].sensor.tempInF * 1.8 + 32).toFixed(2);\n\n",
                "showvalue": 1,
                "initialvalue": "0"
            }
        }],
        "col_width": 1
    }],
    "columns": null,
    "plugins": [],
    "version": 1,
    "allow_edit": true,
    "datasources": []
}

console.log(data.panes);
&#13;
&#13;
&#13;