[英]Unable to access JSON Element in Javascript via Object.property
我无法从JSON结构访问一个简单的JSON元素,如下所示:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
我以JSON格式获取数据,但是当我执行data.ACTION或data.MESSAGE时,我将Undefined作为输出。
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
属性,当您尝试获取未在对象上定义的属性时,您将获得undefined
。
Javascript区分大小写。 您应该尝试使用obj.MESSAGE
来获取属性值。 此外,要检查对象上是否存在属性,可以使用object.hasOwnProperty([propName])
方法检查对象上是否存在属性。
编辑1:尝试运行以下代码段。 在访问属性之前解析JSON数据字符串。
var jsonString = "{\\"ACTION\\":\\"AA\\",\\"MESSAGE\\":\\"Customer No. 0000030332 Already Approved On 20170113\\"}"; var obj = JSON.parse(jsonString); console.log(obj.MESSAGE);
编辑。 我首先想到的是错误是由于解析而造成的。 -.-
解决方案:打印输出时, 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"
data
已经是一个JSON字符串,不需要JSON.stringify
它(它返回一个带有JSON编码的字符串文字的字符串)。 将其解析为output
只会再次导致字符串,该字符串没有属性。 你应该用
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(注意属性名称的正确外壳)
你可以试试:
var jsonObject = data.data;
console.log(jsonObject.ACTION)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.