读取javascript中的Json
我有下面的Json输出,我正在尝试读取sample_rate字段。在阅读之前,我正在检查是否存在任何数据读取javascript中的Json,javascript,json,Javascript,Json,我有下面的Json输出,我正在尝试读取sample_rate字段。在阅读之前,我正在检查是否存在任何数据 { "responseHeader": { "status": 0, "QTime": 0 }, "response": { "numFound": 1, "start": 0, "docs": [ { "sample_rate": 5000 } ] } } 我试图用下面的代码来做这件事
{
"responseHeader": {
"status": 0,
"QTime": 0
},
"response": {
"numFound": 1,
"start": 0,
"docs": [
{
"sample_rate": 5000
}
]
}
}
我试图用下面的代码来做这件事,但得到了错误
TypeError:无法读取未定义的属性“hasOwnProperty”
function(error, response, body){
if(!error && response.statusCode == 200) {
console.log("inside t1");
let tsales = JSON.parse(body);
var tsales2 = JSON.stringify(tsales);
console.log(tsales2);
console.log("inside t2");
if (tsales2.response.hasOwnProperty("docs")) {
console.log("inside t3");
let reply = `${responseText} ${tsales2.response["docs"][0]["sample_rate"]}`;
sendTextMessage(sender, reply);
} else {
let tsales = JSON.parse(body);
console.log("inside t4");
sendTextMessage(sender,
`No sales available for ${parameters["brand"]}`);
}
只用
if (tsales.response.docs)
或
指的是JSON.parse()
- 为什么
JSON.parse(body)
然后JSON.stringify(tsales)?
。如果您想解析
JSON对象,则无需执行JSON.stringify(tsales)
JSON.stringify(tsales)
将JSON对象
转换为JSON字符串
,然后此语句tsales2.response.hasOwnProperty(“docs”)
将返回false,因为tsales2
不再是JSON对象
-
TypeError:无法读取未定义的属性“hasOwnProperty”
function(error, response, body){
if(!error && response.statusCode == 200) {
console.log("inside t1");
let tsales = JSON.parse(body);
var tsales2 = JSON.stringify(tsales);
console.log(tsales2);
console.log("inside t2");
if (tsales2.response.hasOwnProperty("docs")) {
console.log("inside t3");
let reply = `${responseText} ${tsales2.response["docs"][0]["sample_rate"]}`;
sendTextMessage(sender, reply);
} else {
let tsales = JSON.parse(body);
console.log("inside t4");
sendTextMessage(sender,
`No sales available for ${parameters["brand"]}`);
}
这意味着tsales2.response
不存在,或者我们可以说在将其转换为JSON字符串时未定义
JSON.stringify(tsales)
将tsales JSON对象
转换为JSON字符串对象,
,而字符串对象中不会有hasOwnProperty方法
,这就是它返回false并执行else块的原因,以解决这个问题,无需像下面的代码那样对tsales进行stringify
function(error, response, body){
if(!error && response.statusCode == 200) {
console.log("inside t1");
let tsales = JSON.parse(body);
console.log(tsales);
console.log("inside t2");
if (tsales.response.hasOwnProperty("docs")) {
console.log("inside t3");
let reply = `${responseText} ${tsales.response["docs"][0]["sample_rate"]}`;
sendTextMessage(sender, reply);
} else {
let tsales = JSON.parse(body);
console.log("inside t4");
sendTextMessage(sender,
`No sales available for ${parameters["brand"]}`);
}
}
}
将if(tsales2.response.hasOwnProperty(“docs”){
替换为if(tsales2.response.docs){
JSON.stringify
将数据转换为字符串而不是对象。因此,如果您实际上有一个带有JSON.parse
的对象,您应该只使用该-tsales.response.hasOwnProperty(“docs”)
使用JSON.stringify有助于您的控制台.log
输出-但是使用对象来访问代码中的值。并且您不必在最后一个条件块中再次使用JSON.parse。对于let reply=`${responseText}${tsales.response[“docs”][0][“sample_rate”]}`