【问题标题】:Extracting JSON value in Javascript with special character \"用特殊字符\"在Javascript中提取JSON值
【发布时间】:2019-12-10 12:52:18
【问题描述】:

我如何从下面的 json 中提取 text,因为它包含 \" 它给了我一个未定义的

{ 
   "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(Answer: ${JSON.stringify(res.data.answers[0].answer.text)});并且 控制台.log(Answer: ${res.data.answers[0].answer.text});

【问题讨论】:

  • 如果 JSON.parse 不解析 JSON,它就不是 JSON - 当你尝试像这样嵌套 JSON 时,它永远不会漂亮...answer 的值是一个字符串,看起来像JSON

标签: javascript node.js json jsonparser


【解决方案1】:

answer 的值是一个字符串

它不是一个对象,所以它没有text 属性(这就是为什么它是undefined)。

好像是JSON,可以解析一下:

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

请注意,有一个 JSON 文本,其中一个值是另一个 JSON 文本的字符串表示,这是 非常糟糕的数据格式设计的一个好兆头。

更改 API 以将 answer 作为对象而不是对象的 JSON 表示形式返回将是更好的方法。

【讨论】:

  • 有一个拼写错误,我在评论中提到过,如果可能,请编辑 const answer = JSON.parse(res.data.answers[0].answer); const text = answer.text;
【解决方案2】:

您必须执行以下操作 -

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

输入是你给的json。此外,如果您的列表很长并且希望自动解析 json,那么您可以执行以下操作 -

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

上面的代码会自动把你的 json 字符串转成解析过的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-23
    • 2014-07-22
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多