19
{
    "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

PPShein
  • 13,309
  • 42
  • 142
  • 227
  • 2
    Is that JSON in an array? You may need to iterate that, then grab it (`translation[index]["mm"]`) – Sterling Archer Jan 31 '17 at 04:06
  • If it is a JavaScript Object (already parsed from a JSON string), you might be able to access the fields with `translation.mm` or `translation['mm']`. If it's a string, you should parse it first with `JSON.parse(string)`. – mrlew Jan 31 '17 at 04:08
  • @mrlew he already is using `translation["mm"]` as you can see, there's another factor here we're not seeing. – Sterling Archer Jan 31 '17 at 04:09
  • @SterlingArcher sure, was just pointing that it should work **if** it's a JavaScript Object. – mrlew Jan 31 '17 at 04:13

2 Answers2

26

Edited The Answer. Now Its working for above object in question

You can use following function to access the keys of JSON. I have returned 'mm' key specifically.

    function jsonParser(stringValue) {

       var string = JSON.stringify(stringValue);
       var objectValue = JSON.parse(string);
       return objectValue['mm'];
    }
Vikas
  • 666
  • 5
  • 15
  • 1
    he already is using `translation["mm"]` which is correct, this does not answer the issue. The object does not need to be parsed either, it's already valid JSON – Sterling Archer Jan 31 '17 at 04:10
  • 1
    @SterlingArcher JSON always need to be parsed to JavaScript Object. JSON is a string notation. – mrlew Jan 31 '17 at 04:16
17

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;
adonike
  • 1,038
  • 10
  • 8
  • indeed, it's a valid JSON. That's why i suggest to parse it first: to deal with an object instead of dealing with a JSON; since I don't know if it's another variable or anything else. – adonike Jan 31 '17 at 04:18
  • This provided the easiest and best explanation for me. Accepted answer didn't work. – Mario Codes Mar 17 '22 at 12:11