Basel Basel - 3 months ago 11
JSON Question

convert special string to json obj

How can I convert a string like this:

{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 "}


to
json
?

Answer

1) I didn't understand your need, you need just format your text?

if it's true you can use, for example, the Notepad++ JSON Viewer Plugin for this you need select the text and click on:

Plugins->JSON Viewer->Format JSON.

2) Your example is a list of items, then you need include it in "[ ]" and put the field names in "" for a better JSON format, like this:

[
  {
    "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 "
  }
]

You can try your JSON on http://jsonviewer.stack.hu/

3) You didn't told us if you need use this JSON in some program language, then I'll show you a example in Javascript using a converting of your string to JSON Object.

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);