繁体   English   中英

如何在此JSON中访问此键的此值?

[英]How can I access to this value of this key in this JSON?

我想阅读_body内部的错误消息。

目前,我要做的是:

console.log(message._body.error);

但是,我变得不确定。

当我做console.log(message._body);

我收到“ {”代码“:141,”错误“:”此电话号码已经存在!“}”

var message = {  
"_body":"{"code":141,"error":"This phone number exists already!"}",
"status":400,
"ok":false,
"statusText":"Bad Request",
"type":2
};

顺便说一句,以下是从这样的后端来的,我不能更改其格式,也不能删除双引号

   "_body":"{"code":141,"error":"This phone number exists already!"}"

如何阅读错误消息?

听起来您有一个包含有效JSON字符串的属性。

您需要调用JSON.parse()将其转换为实际对象。

删除双引号。 做这个...

"_body":{"code":141,"error":"This phone number exists already!"},

这是一个小提琴...

https://jsfiddle.net/cmht6u8f/1/

  1. 您必须将json修复为正确的格式:

     var message = { "_body":'{"code":141,"error":"This phone number exists already!"}', "status":400, "ok":false, "statusText":"Bad Request", "type":2 }; 
  2. 解析内部json并使用它...

      var err = JSON.parse(message._body); console.log(err.error); 

在您的情况下,您需要在从后端获取错误后使用json()方法将其转换为json。

以下一项应该适合您:

error.json()。错误

console.log(error.json().error)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM