Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JSON数组未按预期进行分析_Javascript_Json_Ejs - Fatal编程技术网

Javascript JSON数组未按预期进行分析

Javascript JSON数组未按预期进行分析,javascript,json,ejs,Javascript,Json,Ejs,我的数据结构如下 [{"type" : "text", "label" : "Some Label"},{"type" : "Other type", "label": "Other label"}],[{"type" : "text", "label" : "Some Label"},{"type" : "Other type", "label": "Other label"}] 我从带有 var formData = $(document.getElementById('form-rend

我的数据结构如下

[{"type" : "text", "label" : "Some Label"},{"type" : "Other type", "label": "Other label"}],[{"type" : "text", "label" : "Some Label"},{"type" : "Other type", "label": "Other label"}]
我从带有

var formData = $(document.getElementById('form-render-data')).data('form');
我无法遍历每个数组并访问其中的每个对象。我已经尝试过对周围的[]进行解析和字符串化,但没有任何区别

使用索引循环只打印字符串中的每个字符。在它被放入数据标记之前,我也不会对它进行字符串化

更新: 由于对我一直试图实现的目标存在一些困惑,我将尽力最好地解释整个过程

正在使用Formbuilder.io构建表单。然后,我从表单导出JSON数据,并使用Sails JS框架将它们存储在MYSQL数据库中。但是,一个会话可能会生成多个表单,因此需要多个数组。然后,我将在请求中返回JSON,而不进行任何字符串化或解析


我也尝试过将JSON封装在方括号中,但仍然没有任何运气

如果您修复了JSON,那么您的代码可以正常工作

var formData=$('#form render data')。data('form');
console.log(formData)


数据
在数组中嵌套了
JSON
。所以,你必须这样对待它

var formData = $('#form-render-data').data('form');

for(var i = 0; i < formData.length; i++) {
    console.log(formData[i].type);
    console.log(formData[i].label);
}

请单击
并创建一个-您告诉我们您解析了数据,但我们如何知道?@mplungjan:OP使用jQuery,如果在初始化期间在
数据-*
属性中找到JSON,它将解析JSON,前提是JSON有效。对-我不确定这是否有效-为什么不
$(“#表单呈现数据”)。数据('form')form render data
元素上的
data form
属性的HTML。此外,JSON是无效的,这将解释我在第一篇文章的评论中指出的LOTA,我知道在我的示例中有多个顶级数组。在解析json之前,我尝试用[and]来包围我的json,使其成为一个数组,但我没有这样的运气。请参阅update@BenBrookes:如果您想要一个数组数组,您可以将
[
放在所拥有数组的开头,
[[{“类型”:“文本”,“标签”:“某些标签”},{“类型”:“其他类型”、“标签”:“其他标签”}]、{“类型”:“文本”、“标签”:“某些标签”}、{“类型”:“其他类型”、“标签”:“其他标签”}]
。现在您有了一个数组,它是有效的JSON。如果没有,您就不能使用.data“是的,它们可以;它们将以字符串的形式获取它。如果
数据
无法解析它找到的内容(以数字、JSON等形式),它以字符串形式返回。@T.J.Crowder-我添加了wrapPlease,单击
并创建一个工作示例-我相信JSON.parse中的构建将fail@mplungjan使用OP的数据为meNot工作:-你像我一样更改了他的数据
[
    {
        "type" : "text",
        "label" : "Some Label"
    },
    {
        "type" : "Other type",
        "label": "Other label"
    }
,
    {
        "type" : "text",
        "label" : "Some Label"
    },
    {
        "type" : "Other type",
        "label": "Other label"
    }
]