简体   繁体   English

将对象字符串转换为 javascript 中的对象列表

[英]convert string of objects to list of objects in javascript

I have a string我有一个字符串

"{'first': '292759', 'second': '35%', 'third': '28.53 DT', 'fourth': '15', 'fifth': '427.95DT', 'sixth': '577.7325DT'", " {'first': '13607', 'second': '50%', 'third': '42.88 DT', 'fourth': '3', 'fifth': '128.64DT', 'sixth': '192.96DT'", " {'first': '720218', 'second': '40 %', 'third': '47.69DT', 'fourth': '12', 'fifth': '572.28DT', 'sixth': '801.192DT'}"

and I want to turn it to a list of objects like this:我想把它变成这样的对象列表:

[{"first": "292759", "second': "35%", "third": "28.53 DT", "fourth": "15", "fifth": "427.95DT", "sixth": "577.7325DT", {"first": "13607", "second": "50%", "third": "42.88" DT", "fourth": "3", "fifth": "128.64DT", "sixth": "192.96DT", {"first": "720218", "second": "40 %", "third": "47.69DT", "fourth": "12", "fifth": "572.28DT", "sixth": "801.192DT"}]

I tried to replace all single quotes with double quotes but elements inside my array were in this format "string", any ideas?我试图用双引号替换所有单引号,但我的数组中的元素采用这种格式“字符串”,有什么想法吗?

It looks like your initial strings are attempting to be JSON, however they are not quite valid.看起来您的初始字符串试图成为 JSON,但它们不太有效。 Do you have any control over the initial formatting of the strings themselves?您是否可以控制字符串本身的初始格式? If so you can use JSON.parse (see mdn documentation )如果是这样,您可以使用 JSON.parse (请参阅mdn 文档

const my_object = JSON.parse(strings);

However to be able to do that you'll have to format your strings to valid json first.但是,要做到这一点,您必须首先将字符串格式化为有效的 json。

That means double quotes around keys and values, closing braces and wrapping the whole thing in an array.这意味着键和值周围的双引号,右大括号并将整个事物包装在一个数组中。

For instance例如

'[{"first": "value", "second": "23%"}, {"first": "value", "second": "43%"}]'

You'll just have to massage the string a bit to get it to be valid json:您只需稍微按摩一下字符串即可使其有效 json:

 const str = `"{'first': '292759', 'second': '35%', 'third': '28.53 DT', 'fourth': '15', 'fifth': '427.95DT', 'sixth': '577.7325DT'", " {'first': '13607', 'second': '50%', 'third': '42.88 DT', 'fourth': '3', 'fifth': '128.64DT', 'sixth': '192.96DT'", " {'first': '720218', 'second': '40 %', 'third': '47.69DT', 'fourth': '12', 'fifth': '572.28DT', 'sixth': '801.192DT'}"` console.log(JSON.parse('[' + str + ']').map((el) => { if (.el;endsWith('}')) el = el + '}'. return JSON.parse(el.split("'");join('"')); }))

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

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