I have 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": {}
}
How to get last object? This is an example, I should have a lot of this objects
I want to have "Cat" from last object, how can I do it? without libraries.
3
Answers
First of all, the JSON is not following the proper semantics, like how can two objects exist in a single JSON without any comma separation?
Assuming, that you are getting an array of these objects, you can simply use the "find()" function to get the object which satisfies the condition. Lets assume the name of the array is "arr" and I am storing the result in "res":
For fetching last object in any array, you can use:
res = arr[arr.length - 1];
res = arr.slice(-1);
res = arr.pop();
Follow the below link for more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
It looks like your "JSON" has been created by appending JSON representations of individual objects, rather than pushing those objects to an array and then returning the JSON representation of that. You should get that software fixed to return valid JSON, but in the interim you can work around the problem by making the string into a JSON representation of an array of objects by adding
[
and]
around it, and replacing occurrences of}{
with},{
. You can then parse it successfully and return thetext
property of the last object in the array:Assuming the separator between each objects might or might not have whitespaces and/or newlines, you can parse the JSON manually instead following the JSON specification here (but with a slight modification of ignoring the ending comma when the depth is
0
– top-level):