gpt4 book ai didi

javascript - 无法通过 Object.property 访问 Javascript 中的 JSON 元素

转载 作者:行者123 更新时间:2023-11-30 11:43:45 25 4
gpt4 key购买 nike

我无法从如下所示的 JSON 结构访问简单的 JSON 元素:

{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}

我以 JSON 格式获取数据,但是当我执行 data.ACTION 或 data.MESSAGE 时,我得到未定义的输出。

通过区分大小写,它不起作用(附图片) enter image description here

var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};

getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED

}, function (status) { //error detection....
alert('Something went wrong.');
});

Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}

stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"

最佳答案

已编辑。考虑到打印品,我首先认为错误是由于解析造成的。 -.-

解决方法:当您打印输出时,obj 它仍然是一个字符串,而不是一个对象。所以那时候没问题。

您的“未定义”属性 message 应替换为 MESSAGE。而不是 console.log(obj.message); 只需使用 console.log(obj.MESSAGE);

还有。解析JSON的例子:

var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"

关于javascript - 无法通过 Object.property 访问 Javascript 中的 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com