英文:
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 = "{\"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);
<!-- 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 = "{\"userId\":44, \"userName\": \"Jim Coleman\"},{\"userId\":33515, \"userName\": \"Grace Mamaradlo\"}";
console.log(JSON.parse(`[${json}]`))
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论