简体   繁体   English

不在数组中的脏JSON对象-如何解析呢?

[英]Dirty JSON objects not in array - how can I parse this?

I'm currently trying to parse the following JSON output. 我目前正在尝试解析以下JSON输出。 These JSON objects are stored in one big string and not in a JSON array. 这些JSON对象存储在一个大字符串中,而不存储在JSON数组中。 As such it is not valid JSON. 因此,它不是有效的JSON。

{"output": "te\ns\nt"}
{"output": "test"}

This string also contains multiple new lines. 此字符串还包含多个新行。 So splitting on new lines is not an option. 因此,拆分新行不是一种选择。

Nevertheless is there any way of parsing this invalid JSON that it results in a valid array of JSON objects? 但是,有什么方法可以解析此无效的JSON,从而导致有效的JSON对象数组?

If your object-list (let's call it that) contains valid objects you can first make an array from each line and then go through that array and parse the JSON: 如果您的对象列表(称为它)包含有效的对象,则可以首先从每一行创建一个数组,然后遍历该数组并解析JSON:

 let data = `{"output": "test"} {"output": "test"}`; //template string to make the newlines work flawless... // first split on newline filter out "" map to the parsed JSON data = data.replace(/}\\n*/g, "}**").split("**") .filter(Boolean) .map(JSON.parse); console.log(data); 

Here's something dirty that might work. 这里有些脏事可能起作用。

let string = `{"output": "te\ns\nt"}
{"output": "test"}`

let json = JSON.parse(`[${string.replace(/}[\s]*\{/g, '}, {').replace(/\n/g, '\\n')}]`)

console.log(json) // [ { output: 'te\ns\nt' }, { output: 'test' } ]

Not pretty and quite fragile, but quick. 不漂亮,很脆弱,但是很快。

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

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