具有多个值的json对象的正确结构

时间:2018-10-22 13:17:37

标签: javascript json

我正在创建一个图形(GANTT图形),我需要将包含所有值的JSON文件传递给插件以构建图形。 插件的示例json是这样的:

source: [{
    name: "Example",
    desc: "Lorem ipsum dolor sit amet.",
    values: [{
        to: "/Date(1328832000000)/",
        from: "/Date(1333411200000)/",
        desc: "Something",
        label: "Example Value",
        customClass: "ganttRed",
        dataObj: foo.bar[i]
    }]
},
{
    name: "Example1",
    desc: "Stackoverflow rulez.",
    values: [{
        to: "/Date(1328832000000)/",
        from: "/Date(1333411200000)/",
        desc: "Something else",
        label: "Example Value 1",
        customClass: "ganttGreen",
        dataObj: foo.bar[i]
    }]
}]

我添加了Example1元素,然后尝试使用JSONLint进行验证,以确保我以正确的方式构建Array。令我惊讶的是,验证器说出第一个[{之后的语法无效(很显然,我没有将source:传递给验证器)。 我收到的错误消息是:

Error: Parse error on line 1:
[{    name: "Example",    de
--^
Expecting 'STRING', '}', got 'undefined'

我在做什么错?验证器为什么会引发此错误? Json是使用Notepad ++以纯txt格式编写的,因此我无法想到空格中的隐藏文本

2 个答案:

答案 0 :(得分:0)

要将数据传递为有效的JSONLint,请将json对象中的所有键包装为字符串。

您输入的有效json是

"source": [{
    "name": "Example",
    "desc": "Lorem ipsum dolor sit amet.",
    "values": [{
        "to": "/Date(1328832000000)/",
        "from": "/Date(1333411200000)/",
        "desc": "Something",
        "label": "Example Value",
        "customClass": "ganttRed",
        "dataObj": foo.bar[i]
    }]
},
{
    "name": "Example1",
    "desc": "Stackoverflow rulez.",
    "values": [{
        "to": "/Date(1328832000000)/",
        "from": "/Date(1333411200000)/",
        "desc": "Something else",
        "label": "Example Value 1",
        "customClass": "ganttGreen",
        "dataObj": foo.bar[i]
    }]
}]

答案 1 :(得分:0)

将您键入双引号。它会工作

"source":[
    {
        "name": "Example",
        "desc": "Lorem ipsum dolor sit amet.",
        "values": [{
            "to": "/Date(1328832000000)/",
            "from": "/Date(1333411200000)/",
            "desc": "Something",
            "label": "Example Value",
            "customClass": "ganttRed",
            "dataObj": foo.bar[i]
        }]
    },
    {
        "name": "Example1",
        "desc": "Stackoverflow rulez.",
        "values": [{
            "to": "/Date(1328832000000)/",
            "from": "/Date(1333411200000)/",
            "desc": "Something else",
            "label": "Example Value 1",
            "customClass": "ganttGreen",
            "dataObj": foo.bar[i]
        }]
    }
]

请参见下面的屏幕快照以获取有效的json

enter image description here