Amit
Amit

Reputation: 47

Convert JSON Array to Sequence of JSON Object

I have JSON Array String

[
    { "ok": true },
    { "ok": true },
    { "ok": true },
    { "ok": true },
    { "ok": true }
]

I want to convert JSON Array String to Sequence of JSON Objects string like

{"ok":true}
{"ok":true}
{"ok":true}
{"ok":true}
{"ok":true}

I used jsonarraystring.replace(/,{/g , "\n{") but it is not safe.

Is there any library in javascript to handle this?

Upvotes: 2

Views: 374

Answers (3)

Vivek Buddhadev
Vivek Buddhadev

Reputation: 397

If you are looking for other options you can use $.parseJSON()

function () {
      var str = '[{ "ok": true },{ "ok": false },{ "ok": true }]';

      var jsonObjArray = $.parseJSON(str);

      for(var i=0;i<jsonObjArray.length;i++){
          alert(jsonObjArray[i]["ok"]);
      }            
}

Upvotes: 0

The @Shanimal's answer is correct.

You can test the code, by this way:

(function() {
  var jsonarraystring =
  [
      { "ok": true },
      { "ok": true },
      { "ok": true },
      { "ok": true },
      { "ok": true }
  ];


  console.log(jsonarraystring.map(JSON.stringify).join("\n"));

})();

Upvotes: 1

Shanimal
Shanimal

Reputation: 11718

[
    { "ok": true },
    { "ok": true },
    { "ok": true },
    { "ok": true },
    { "ok": true }
].map(JSON.stringify).join("\n")

Upvotes: 3

Related Questions