简体   繁体   English

如何将逗号分隔的 JS 多对象字符串转换为 js 对象或 json?

[英]How convert JS Multiple Object string seperated by comma to js object or json?

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.如何将此字符串转换为 js 对象或 json 以通过 foreach 访问它。

You need to transform your string to a Json able string first, then parse it.您需要先将字符串转换为支持Json字符串,然后再解析它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM