简体   繁体   English

解析JavaScript中的非标准JSON

[英]Parsing non-standard JSON in JavaScript

I am receiving a non-standard JSON format from a request.我收到来自请求的非标准 JSON 格式。 How one can convert or parse this kind of non-standard format in JavaScript or any other scripting language?如何在 JavaScript 或任何其他脚本语言中转换或解析这种非标准格式?

{
    "count": 2,
    "sales": [
        {
            "id": 1195816,
            "city": "New York",
            "name": "testing1"
        },
        {
            "id": 1195815,
            "city": "LA",
            "name": "testing2"
        }
    ],
    "total_sales_count": 148393,
    "date": "17.04.2020"
}
{
    "count": 2,
    "sales": [
        {
            "id": 1195816,
            "city": "Washington",
            "name": "testing3"
        },
        {
            "id": 1195815,
            "city": "New Jersey",
            "name": "testing4"
        }
    ],
    "total_sales_count": 49403,
    "date": "17.04.2020"
}

So you have multiple JSON objects concatenated, separated with a newline.所以你有多个 JSON 对象连接,用换行符分隔。

A quick hack that might just work is to add a comma between the objects and wrap them in an array.一个可能可行的快速技巧是在对象之间添加一个逗号并将它们包装在一个数组中。

> JSON.parse(`[${json.replace(/\}\n\{/g, '},{')}]`);
(2) [{…}, {…}]

I am receiving a non-standard JSON...我收到一个非标准的 JSON...

In fact, there is a standard.其实是有标准的。 Line-delimited, or ND-JSON.行分隔,或 ND-JSON。 http://ndjson.org/ http://ndjson.org/

It's desirable to use this format when returning multiple records.返回多条记录时最好使用这种格式。 It allows you to stream the response, and parse without having to load the entire dataset into memory at the same time.它允许您对 stream 响应进行解析,而无需同时将整个数据集加载到 memory 中。

To parse in JavaScript, I'd pick up one of the several standard packages available for this.为了解析 JavaScript,我会选择几个可用的标准包之一。 For example: https://www.npmjs.com/package/ndjson例如: https://www.npmjs.com/package/ndjson

fs.createReadStream('data.txt')
  .pipe(ndjson.parse())
  .on('data', function(obj) {
    // obj is a javascript object
  })

If you want to do this in a browser that supports transform streams, here's some code from one of my projects you can adapt:如果您想在支持转换流的浏览器中执行此操作,以下是我的一个项目中的一些代码,您可以调整:

return res.body
    // Decode as UTF-8 Text
    .pipeThrough(new TextDecoderStream())

    // Split on lines
    .pipeThrough(new TransformStream({
      transform(chunk, controller) {
        textBuffer += chunk;
        const lines = textBuffer.split('\n');
        for (const line of lines.slice(0, -1)) {
          controller.enqueue(line);
        }
        textBuffer = lines.slice(-1)[0];
      },
      flush(controller) {
        if (textBuffer) {
          controller.enqueue(textBuffer);
        }
      }
    }))

    // Parse JSON objects
    .pipeThrough(new TransformStream({
      transform(line, controller) {
        if (line) {
          controller.enqueue(JSON.parse(line));
        }
      }
    }));

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

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