如何解析没有逗号的JSON?Node.js

vnzz0bqm  于 2023-05-02  发布在  Node.js
关注(0)|答案(3)|浏览(318)

JSON:

{
  "entities": {},
  "intents": [],
  "speech": {
    "confidence": 0.4471,
    "tokens": [
      {
        "confidence": 0.4471,
        "end": 1560,
        "start": 560,
        "token": "Кот"
      }
    ]
  },
  "text": "Кот",
  "traits": {}
}
{
  "entities": {},
  "intents": [],
  "is_final": true,
  "speech": {
    "confidence": 0.4471,
    "tokens": [
      {
        "confidence": 0.4471,
        "end": 1560,
        "start": 560,
        "token": "Кот"
      }
    ]
  },
  "text": "Cat",
  "traits": {}
}

如何获取最后一个对象?这是一个例子,我应该有很多这个对象,我想有“猫”从最后一个对象,我怎么能做到这一点?没有图书馆。

wydwbb8l

wydwbb8l1#

看起来你的“JSON”是通过附加单个对象的JSON表示来创建的,而不是将这些对象推送到一个数组中,然后返回该对象的JSON表示。您应该修复该软件以返回有效的JSON,但在此期间,您可以通过在字符串周围添加[],并将}{替换为},{,将字符串转换为对象数组的JSON表示来解决这个问题。然后你可以成功解析它,并返回数组中最后一个对象的text属性:

jstr = `{
  "entities": {},
  "intents": [],
  "speech": {
    "confidence": 0.4471,
    "tokens": [
      {
        "confidence": 0.4471,
        "end": 1560,
        "start": 560,
        "token": "Кот"
      }
    ]
  },
  "text": "Кот",
  "traits": {}
}
{
  "entities": {},
  "intents": [],
  "is_final": true,
  "speech": {
    "confidence": 0.4471,
    "tokens": [
      {
        "confidence": 0.4471,
        "end": 1560,
        "start": 560,
        "token": "Кот"
      }
    ]
  },
  "text": "Cat",
  "traits": {}
}`

jstr = '[' + jstr.replace(/}\s*\{/, '},{') + ']'

arr = JSON.parse(jstr)
console.log(arr[arr.length-1].text)
9ceoxa92

9ceoxa922#

首先,JSON没有遵循正确的语义,比如两个对象如何在没有任何逗号分隔的情况下存在于一个JSON中?假设你得到了一个包含这些对象的数组,你可以简单地使用“find()”函数来得到满足条件的对象。让我们假设数组的名称是“arr”,我将结果存储在“res”中:

let res = arr.find(ele => ele.text === "Cat");

要获取任何数组中的最后一个对象,可以用途:
1.长度属性,如res = arr[arr.length - 1];
1.像res = arr.slice(-1);这样切片方法

  1. pop方法,如res = arr.pop();
    点击以下链接了解更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
ttp71kqs

ttp71kqs3#

假设每个对象之间的分隔符可能有也可能没有空格和/或换行符,您可以手动解析JSON,而不是按照这里的JSON specification(但当深度为0- top-level时忽略结尾逗号):

function extractJSONWithoutComma(input) {
  const output = [];

  let startBoundary = 0;
  let depth = 0;
  let inQuote = false;

  // We don't count the depth of array here assuming the top-level is all objects
  // We didn't check the validity of the JSON here, just trying to find the separator

  for (let i = 0; i < input.length; i++) {
    const char = input[i];

    // The only key to end a quote is another "
    // The reason why we need to know is it inside a string or not is to prevent from { inside the string
    if (inQuote) {
      if (char === '\\') {
        i++; // Skip one character
        continue;
      }
      if (char === '"') {
        inQuote = false;
      }
      continue;
    }

    switch (char) {
      case '{':
        if (depth === 0) startBoundary = i;
        depth++;
        break;
      case '}':
        depth--;
        // When depth matched 0, it means this is an object separator
        if (depth === 0) {
          output.push(JSON.parse(input.substring(startBoundary, i + 1)));
        }
        break;
      case '"':
        inQuote = true;
        break;
    }
  }

  return output;
}

const testCase1 = `{
  "entities": {},
  "intents": [],
  "speech": {
    "confidence": 0.4471,
    "tokens": [
      {
        "confidence": 0.4471,
        "end": 1560,
        "start": 560,
        "token": "Кот"
      }
    ]
  },
  "text": "Кот",
  "traits": {}
}
{
  "entities": {},
  "intents": [],
  "is_final": true,
  "speech": {
    "confidence": 0.4471,
    "tokens": [
      {
        "confidence": 0.4471,
        "end": 1560,
        "start": 560,
        "token": "Кот"
      }
    ]
  },
  "text": "Cat",
  "traits": {}
}`;

const testCase2 = '{"a":1}{"b":2}';
const testCase3 = '{"a":"{}}"}{"b":2}';
const testCase4 = '{"a":"{}   {"}{"b":2}'; // The string inside a gets converted to },{ unexpectedly if using naive solution of replacing all `}\s*{` to `},{`

console.log(extractJSONWithoutComma(testCase1));
console.log(extractJSONWithoutComma(testCase2));
console.log(extractJSONWithoutComma(testCase3));
console.log(extractJSONWithoutComma(testCase4));

// And to get your last object:

const result = extractJSONWithoutComma(testCase1);
console.log(result[result.length - 1].text);

相关问题