我需要一些帮助将JSON字符串转换为JSON对象。 这是我的变量:
var myString= "{ title: 'mySchema'," + "root: {id:'" + var1 + "'," + "title:'" + var2 + "'," + "subtitle:'" + var3 + "',";
childrenVar = myString + "{ id: '" + var1 + "'," + "title: '" + var2 + "'," + "subtitle: '" + var3 + "'," + "type: '" + var4 + "'";
myString= getChildNodes(tasksEntries, head, liststring);
myString= myString + "},";}
myString= myString+ "]}}"; }
myString= childrenVar;
myString= childrenVar;
JSON.stringify(myString);
$.parseJSON(myString);
我在调试时输出myString
:
{title: 'mySchema',
root: {
id:'1',
title:'oOB',
subtitle:'Hang Chaw',
children: [
{
id: '2',
title: 'OaK',
subtitle: 'Ke Man',
type: 'VA'
},
{
id: '3',
title: 'OOB',
subtitle: 'Hung Aslew',
type: 'VA'
},
]
}
};
答案 0 :(得分:0)
删除close array(]之前的最后一个逗号。
答案 1 :(得分:0)
您还需要围绕对象键引用。一个合适的JSON字符串看起来像下面的字符串。 jQuery.parseJSON
这是一个示例Fiddle,其中字符串转换为对象,然后记录到控制台。
var myString = '{"title": "mySchema","root": {"id":"1","title":"oOB","subtitle":"Hang Chaw","children": [{ "id": "2","title": "OaK","subtitle": "Ke Man","type": "VA"},{ "id": "3","title": "OOB","subtitle": "Hung Aslew","type": "VA"}]}}';
使用JSON.parse,这是相同的Fiddle。最新版本的JavaScript本身支持JSON。如果您只使用jQuery来解析JSON字符串,那么您应该使用JSON.parse,而不是包含jQuery库。