1

How can i extract text from the below json, As it contains \" it is giving me an undefined

{ 
   "answers":[ 
      { 
         "questions":[  ],
         "answer":"{\"text\":\"I am Ellina. I can't believe you forgot my name\",\"speech\":\"I am Ellina. I can't believe you forgot my name\"}",
         "score":100,
         "id":106,
         "source":"Editorial",
         "metadata":[ 

         ],
         "context":{ 
            "isContextOnly":false,
            "prompts":[ 

            ]
         }
      }
   ],
   "debugInfo":null,
   "activeLearningEnabled":false
}

i tried using console.log(Answer: ${JSON.stringify(res.data.answers[0].answer.text)}); and also console.log(Answer: ${res.data.answers[0].answer.text});

Vinay Jayaram
  • 1,030
  • 9
  • 29
  • 1
    if `JSON.parse` doesn't parse the JSON, it's not JSON - it's never pretty when you try to have nested JSON like that ... value of `answer` is a string, that looks like JSON – Jaromanda X Dec 10 '19 at 12:53

2 Answers2

6

The value of answer is a string.

It isn't an object so it doesn't have a text property (which is why it is undefined).

It appears to be JSON, so you can parse it:

const answer = JSON.parse(es.data.answers[0].answer);
const text = answer.text;

Note that having a JSON text where one of the values in it is a string representation of another JSON text is a good sign of really bad data format design.

Changing the API so it returns answer as an object instead of a JSON representation of an object would be a better approach.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • There was a typo error, i have mentioned in the comment, Edit if possible const answer = JSON.parse(res.data.answers[0].answer); const text = answer.text; – Vinay Jayaram Dec 10 '19 at 17:19
1

You will have to do the following -

let parsed = JSON.parse(input.answers[0].answer);

where input is the json given by you. Also if you have a long list and you want the json to be parsed automatically then you can do something like this -

input.answers = input.answers.map((answer)=>{
    answer.answer = JSON.parse(answer.answer);
    return answer;
})

The above code will automatically turn your json string to a parsed JSON.

let input = {
  "answers": [{
    "questions": [],
    "answer": "{\"text\":\"I am Ellina. I can't believe you forgot my name\",\"speech\":\"I am Ellina. I can't believe you forgot my name\"}",
    "score": 100,
    "id": 106,
    "source": "Editorial",
    "metadata": [

    ],
    "context": {
      "isContextOnly": false,
      "prompts": [

      ]
    }
  }],
  "debugInfo": null,
  "activeLearningEnabled": false
}

console.log(input);

input.answers = input.answers.map((answer) => {
  answer.answer = JSON.parse(answer.answer);
  return answer;
});

console.log(input);
yawningphantom
  • 386
  • 1
  • 3
  • 9