Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from specific key in NodeJS JSON [duplicate]

Tags:

json

node.js

{
    "id": 83,
    "key": "hello",
    "en": "Hello",
    "mm": "This is greeting",
    "created_at": "2016-12-05T10:14:02.928Z",
    "updated_at": "2017-01-31T02:57:11.181Z"
}

I'm trying to get value from mm key in NodeJS. I've tried to get translation["mm"] but it does not work at all. Please help me how to get mm from above data.

My current node version is 5.11

like image 243
PPShein Avatar asked Jan 31 '17 04:01

PPShein


People also ask

How does JSON handle duplicate keys?

What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

Can JSON have duplicate fields?

The short answer: Yes but is not recommended.

How do you get a specific value from a JSON string?

getJsonString() Method It is used to get the (JsonString)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the String value of the associated mapping for the parsed parameter. It returns null if the object has no mapping for the parameter.

Can JSON have same key?

There is no "error" if you use more than one key with the same name, but in JSON, the last key with the same name is the one that is going to be used. In your case, the key "name" would be better to contain an array as it's value, instead of having a number of keys "name".


1 Answers

JSON is an interchange format, meaning it's only a text representing data in a format that many applications can read and translate into it's own language.

Therefore, using node.js you should parse it first (translate it to a javascript object) and store the result in a variable:

var obj = JSON.parse(yourJSONString);

Then, you can ask for any of it properties:

var mm = obj.mm;
like image 91
adonike Avatar answered Oct 23 '22 02:10

adonike