首页 > 解决方案 > 如何在javascript中过滤json?

问题描述

好的,所以我的代码从 websocket 检索 json 并且当前将所有 json 打印到控制台。我想要做的是将信息片段存储为变量。我该如何转:

{
    "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"
        }
    ]

进入:

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

我正在使用节点。

标签: javascriptjson

解决方案


这提供了你想要的。单击下面的“运行代码片段”以查看输出。

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);    
})


推荐阅读