简体   繁体   English

如何使用js从无效的json字符串中提取最后一个元素

[英]How to extract the last element out of an invalid json string with js

I'm using a nodejs speech recognition API that returns a string with multiple texts inside a JSON like structure which is invalid and unusable我正在使用 nodejs 语音识别 API,该 API 返回一个字符串,其中包含一个无效且不可用的类似 JSON 的结构中的多个文本

{
  "text": "Play"
}
{
  "text": "Play astronaut"
}
{
  "text": "Play astronaut in the"
}
{
  "text": "Play astronaut in the ocean"
}
{
  "entities": {},
  "intents": [],
  "text": "Play astronaut in the ocean.",
  "traits": {}
} 

and I only want last element which is我只想要最后一个元素

{
  "entities": {},
  "intents": [],
  "text": "Play astronaut in the ocean.",
  "traits": {}
}

by filtering it out or something to extract the text "Play astronaut in the ocean."通过过滤掉它或其他东西来提取文本“在海洋中玩宇航员”。

The API always outputs multiple text elements in different quantities each time, but I want the last element is that possible? API 每次总是输出不同数量的多个文本元素,但我希望最后一个元素可能吗? or should I find a different API that's usable?或者我应该找到一个不同的可用 API?

Assuming the response is returned as an array, ie [{ "text": "Play" }, { next one.. }] etc假设响应以数组形式返回,即 [{ "text": "Play" }, { next one.. }] 等

Then you can get the last element in the array by variablising the array, get its length, and find the last object.然后你可以通过对数组进行变量化来获取数组中的最后一个元素,获取它的长度,并找到最后一个对象。

eg例如

const x = [{ text.. }, { text.. }]
const lastItem = x[x.length - 1]

Then if you also want to find the last item within that object, you could also do that with Object.values然后,如果你还希望该对象找到的最后一个项目,你也可以做到这一点与Object.values

const lastItemObject = Object.values(lastItem)
const lastItemInTheObject = lastItemObject[lastItemObject.length - 1]

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

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