-1

Ok, so my code retrieves json from a websocket and currently prints all the json to console. What I want to do is store pieces of information as variables. How can I turn:

{
    "type": "question",
    "ts": "2018-06-30T00:05:53.685Z",
    "totalTimeMs": 10000,
    "timeLeftMs": 10000,
    "questionId": 46220,
    "question": "In wrestling, what term refers to pretending that scripted theatrics are totally real?",
    "category": "Entertainment",
    "answers": [{
            "answerId": 140757,
            "text": "Gas"
        },
        {
            "answerId": 140758,
            "text": "Kayfabe"
        },
        {
            "answerId": 140759,
            "text": "House show"
        }
    ]

Into:

    Question = In wrestling, what term refers to pretending that scripted theatrics are totally real?
pAnswer1 = Gas
pAnswer2 = Kayfabe
pAnswer3 = House show

I'm using node.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 2
    The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Oct 15 '18 at 23:38
  • This is what you want - https://stackoverflow.com/questions/5726729/how-to-parse-json-using-node-js – Upamanyu Sundaram Oct 15 '18 at 23:40

1 Answers1

0

This provides what you want. Click "Run code snippet" below to see the output.

const obj = {
 "type": "question",
 "ts": "2018-06-30T00:05:53.685Z",
 "totalTimeMs": 10000,
 "timeLeftMs": 10000,
 "questionId": 46220,
 "question": "In wrestling, what term refers to pretending that scripted theatrics are totally real?",
 "category": "Entertainment",
 "answers": [{
  "answerId": 140757,
  "text": "Gas"
 }, {
  "answerId": 140758,
  "text": "Kayfabe"
 }, {
  "answerId": 140759,
  "text": "House show"
 }]
}

const question = obj.question;
const pAnswer = obj.answers.map(ans => ans.text);

console.log('question =', question);
pAnswer.forEach((ans, i) => {
  console.log(`answer${i+1} =`, ans);    
})
danday74
  • 52,471
  • 49
  • 232
  • 283