如何解析已使用反斜杠字符串化的对象数组

huangapple go评论58阅读模式
英文:

How to parse object array that has been stringified using backslashes

问题

我一直在寻找将此字符串转换为JSON的正确正则表达式如果数组中只有一个对象则可以正常工作但我认为逗号可能会导致问题

const json = "{\"userId\":44, \"userName\": \"Jim Coleman\"},{\"userId\":33515, \"userName\": \"Grace Mamaradlo\"}";
const obj = JSON.parse(json.replace(/("["^"]*"\s*:\s*)(\d{17,})/g, '$1"$2"'));

console.log(obj);
英文:

I have been searching for the correct regex for converting this string to JSON. It works if there is a single object in the array, but I believe the comma is messing it up somehow.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const json = &quot;{\&quot;userId\&quot;:44, \&quot;userName\&quot;: \&quot;Jim Coleman\&quot;},{\&quot;userId\&quot;:33515, \&quot;userName\&quot;: \&quot;Grace Mamaradlo\&quot;}&quot;;
const obj = JSON.parse(json.replace(/(&quot;[^&quot;]*&quot;\s*:\s*)(\d{17,})/g, &#39;$1&quot;$2&quot;&#39;));

console.log(obj);

<!-- end snippet -->

答案1

得分: 0

除了对象列表未包含在方括号内之外,没有其他问题。

const json = "{\"userId\":44, \"userName\": \"Jim Coleman\"},{\"userId\":33515, \"userName\": \"Grace Mamaradlo\"}";
console.log(JSON.parse(`[${json}]`))
英文:

There was nothing wrong except that the list of objects was not contained within square brackets

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const json = &quot;{\&quot;userId\&quot;:44, \&quot;userName\&quot;: \&quot;Jim Coleman\&quot;},{\&quot;userId\&quot;:33515, \&quot;userName\&quot;: \&quot;Grace Mamaradlo\&quot;}&quot;;

console.log(JSON.parse(`[${json}]`))

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 08:54:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490484.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定