我收到服务电话的回复:
var response = "\" {\\\"errcode\\\":1,\\\"errmsg\\\":\\\"ok\\\",\\\"data\\\":\\\"https:\\\\/\\\\/mp.weixin.qq.com\\\\/cgi-bin\\\\/showqrcode?ticket=gQH38DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYTZKU1pzczJhdmUxWHZ6MzFvMTcAAgTfurtYAwQA6QcA\\\"}\""
我解码并获得了
var responseAfterDecode = decodeURI(response);
// responseAfterDecode
"{\"errcode\":1,\"errmsg\":\"ok\",\"data\":\"https:\\/\\/mp.weixin.qq.com\\/cgi-bin\\/showqrcode?ticket=gQH38DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYTZKU1pzczJhdmUxWHZ6MzFvMTcAAgTfurtYAwQA6QcA\"}"
之后我解析了JSON:
var JSONAfterParse = JSON.parse(responseAfterDecode);
// JSONAfterParse =
{"errcode":1,"errmsg":"ok","data":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQH38DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYTZKU1pzczJhdmUxWHZ6MzFvMTcAAgTfurtYAwQA6QcA"}
这看起来像一个完美的JSON。但是当我试图访问
时JSONAfterParse.data --> undefined.
无法弄清楚出了什么问题。
答案 0 :(得分:1)
您尝试从STRING而不是从Object访问属性,您需要使用JSON.parse(string)
...
var JSONAfterParse = '{"errcode":1,"errmsg":"ok","data":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQH38DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYTZKU1pzczJhdmUxWHZ6MzFvMTcAAgTfurtYAwQA6QcA"}';
var ParsedJSON = JSON.parse(JSONAfterParse);
console.log(ParsedJSON.data);
答案 1 :(得分:1)
看起来你实际上有双字符串化的JSON(JSON字符串表示的字符串表示)。这意味着在单个JSON.parse
之后,您仍然会返回一个字符串(因此缺少任何data
属性)。呸。但是,您可以通过再次解析JSON来解决问题:
var response = "\" {\\\"errcode\\\":1,\\\"errmsg\\\":\\\"ok\\\",\\\"data\\\":\\\"https:\\\\/\\\\/mp.weixin.qq.com\\\\/cgi-bin\\\\/showqrcode?ticket=gQH38DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYTZKU1pzczJhdmUxWHZ6MzFvMTcAAgTfurtYAwQA6QcA\\\"}\""
var responseAfterDecode = decodeURI(response)
var jsonAfterParse = JSON.parse(JSON.parse(responseAfterDecode))
console.log(jsonAfterParse.data)
答案 2 :(得分:0)
var response = "\" {\\\"errcode\\\":1,\\\"errmsg\\\":\\\"ok\\\",\\\"data\\\":\\\"https:\\\\/\\\\/mp.weixin.qq.com\\\\/cgi-bin\\\\/showqrcode?ticket=gQH38DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYTZKU1pzczJhdmUxWHZ6MzFvMTcAAgTfurtYAwQA6QcA\\\"}\""
var responseAfterDecode = decodeURI(response);
var js =JSON.parse(responseAfterDecode);
js = JSON.parse(js);
console.log(js.data);