如何转换这样的字符串:
{listId:"4",title:"List 4"},{listId:"5",title:"List 5"},{listId:"6",title:"List 6"},{listId:"7",title:"List 7 "},{listId:"8",title:"List 8 "}
到json
?
答案 0 :(得分:1)
1)我不了解你的需要,你需要格式化你的文字吗?
如果它是真的,你可以使用,例如,Notepad ++ JSON Viewer插件,你需要选择文本,然后点击:
插件 - > JSON Viewer->格式化JSON。
2)您的示例是项目列表,然后您需要将其包含在" []"并将字段名称放在""为了更好的JSON格式,像这样:
[
{
"listId": "4",
"title": "List 4"
},
{
"listId": "5",
"title": "List 5"
},
{
"listId": "6",
"title": "List 6"
},
{
"listId": "7",
"title": "List 7 "
},
{
"listId": "8",
"title": "List 8 "
}
]
您可以在http://jsonviewer.stack.hu/
上试用您的JSON3)您没有告诉我们您是否需要在某种程序语言中使用此JSON,然后我将使用您的字符串转换为JSON对象向您展示Javascript中的示例。
var youExample = '{listId:"4",title:"List 4"},{listId:"5",title:"List 5"},{listId:"6",title:"List 6"},{listId:"7",title:"List 7 "},{listId:"8",title:"List 8 "}';
/* Create a replaceALL to help us. */
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
/* include " in fieldNames */
youExample = youExample.replaceAll("listId", "\"listId\"");
youExample = youExample.replaceAll("title", "\"title\"");
/* include [] */
youExample = "[" + youExample + "]";
console.log(youExample);
/* Convert JSON String to Object */
var jsonObj = JSON.parse(youExample);
console.log(jsonObj);