NEETHU VIJAYAN
NEETHU VIJAYAN

Reputation: 33

Convert an array in string format to javascript array

I have an array which is in string format,

var str = { 
    id: 123,
    changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}
var d = str.changes

I tried to convert the 'changes' array from string format using different methods by combining split(), replace(), slice() etc...and even JSON.parse(), but nothing worked.

Is there any way to convert this into javascript array?

Upvotes: 3

Views: 364

Answers (2)

mplungjan
mplungjan

Reputation: 177692

Note that the string is not valid anything but string. It is not a valid array, and the string is not valid JSON.

If you can, get the server to change it to the valid JSON string

"[{\"atr\":\"test1\", \"old\":null, \"new\":null}, {\"atr\":\"messageText\", \"old\":\"test here\", \"new\":\"hello test\"}, {\"atr\":\"status\", \"old\":null, \"new\":1}]"

If the response is ALWAYS on the format you gave, then you can create valid JSON

var str = {
  id: 123,
  changes: "[[atr:test1, old:null, new:null], [atr:messageText, old:test here, new:hello test], [atr:status, old:null, new:1]]"
}

// change the inner [ ] to { }
let changes = str.changes.replace(/\[\[/g, "[{").replace(/\], \[/g, "},{").replace(/\]\]/g, "}]")

// change the unquoted keys and values to quoted keys and values
changes = changes.replace(/(\w+):/g, '"$1":').replace(/:([\w ]+)([},])/g, ':"$1"$2')

// parse the object
changes = JSON.parse(changes);

// replace "null" with null - could have been done above bt the regex would be nasty
changes.forEach(item => Object.keys(item).forEach(key => item[key] = item[key] === "null" ? null : item[key]))

console.log(changes)

Upvotes: 2

Rajeev Kumar Sharma
Rajeev Kumar Sharma

Reputation: 11

I think the problem is that the key 'changes' do not any valid JSON. You can validate, format it here.

If there is a valid JSON in 'changes' key, It can be converted to Js array using JSON.parse();, Something like:

    var str = { id: 123,
            changes: `[
  [
    {
      "atr": "test1",
      "old": null,
      "new": null
    }
  ],
  [
    {
      "atr": "messageText",
      "old": "test here",
      "new": "hello test"
    }
  ],
  [
    {
      "atr": "status",
      "old": null,
      "new": 1
    }
  ]
]`
          }
var d = JSON.parse(str.changes);

    console.log(d);

//str.changes Object:
[[[object Object] {
  atr: "test1",
  new: null,
  old: null
}], [[object Object] {
  atr: "messageText",
  new: "hello test",
  old: "test here"
}], [[object Object] {
  atr: "status",
  new: 1,
  old: null
}]]

Upvotes: 0

Related Questions