-2

I have a string like this

"{ identifier: '496006074',  amount: 349.90, currency: 'TRY', quantity: 1},{ identifier: '490703697',  amount: 1386.99, currency: 'TRY', quantity: 1},{ identifier: '401364283',  amount: 389.90, currency: 'TRY', quantity: 1}"

how can I convert this string into js object or json to access it by foreach.

Alon Eitan
  • 11,798
  • 8
  • 44
  • 56
talha
  • 11
  • 3
  • 4
    Why do you have faulty JSON? Where are you getting it from? It is *usually* easier to make the source system produce correct JSON than pre-process it and try to guess the correct format. – VLAZ Jan 29 '20 at 09:00
  • Hi! Please read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Jan 29 '20 at 09:00

1 Answers1

0

You need to transform your string to a Jsonable string first, then parse it.

let x = "{ identifier: '496006074',  amount: 349.90, currency: 'TRY', quantity: 1},{ identifier: '490703697',  amount: 1386.99, currency: 'TRY', quantity: 1},{ identifier: '401364283',  amount: 389.90, currency: 'TRY', quantity: 1}"

let array = JSON.parse(`[${x.replace(/([a-zA-Z0-9_]*):/mg, '"$1":').replace(/[']/g, '"')}]`);

console.log(array);
cybercoder
  • 2,433
  • 1
  • 16
  • 24