在JSON.parse函数中传递外部变量 [英] Passing a external variable in JSON.parse function

查看:93
本文介绍了在JSON.parse函数中传递外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSON.parse函数从json获取值,我的json响应在下面给出

Hi i am trying to get a value from a json by using JSON.parse function my json response is given below

{
"rows": 10,
"os": "0",
"page": "1",
"total": "122",
"projects": {
"P143841": {
"id": "P143841",
"locations": [
{
"geoLocId": "0002220957",
"latitude": "3.866667",
"longitude": "11.516667"
}
],
}
}
}

如果执行JSON.parse(obj.rows);,我可以得到值10,但是如果我将行分配给变量,例如var value = rows,然后将其传递给JSON.parse(obj.value)函数,则得到undefined.

I am able to get the value 10 if I do JSON.parse(obj.rows); but if I assign the rows to a variable say var value = rows and then I pass it to the JSON.parse(obj.value) function I got undefined.

P.S我将不知道响应参数的名称(即,如果我引用以上示例,我将不知道它是行还是os).我将从数据库中检索它们 如果我执行以下代码

P.S I wont be knowing the names of the response parameters(ie) i wont know if it will be rows or os if i quote from the above example. I will be retrieving them from a database If i perform the below code

for(var i=0;i<length;i++){
var value = responseParam_array[i];
console.log(obj.value);
}

我得到了输出,但是任何帮助将不胜感激.

I get the output but .Any help will be much appreciated.

推荐答案

根据其他答案,您不必解析单个属性,只需解析原始JSON,然后对生成的对象进行操作即可.

As per the other answers you shouldn't need to parse individual properties, just parse the original JSON and then operate on the resulting object.

但是对于这个问题:

",如果我将行分配给变量,例如 var value = rows ,然后将其传递给获得的 JSON.parse(obj.value) 函数 undefined"

如果value是持有obj属性名称的变量,则您需要:

If value is a variable holding the name of a property of obj then you need:

obj[value]
// NOT
obj.value

使用点"表示法时,点右侧的部分将作为属性的文字名称,而不是变量.使用方括号语法评估括号中的表达式,并将其结果用作属性名称.

When you use "dot" notation the part on the right of the dot is taken as the literal name of the property, not as a variable. Using the square-bracket syntax the expression in the brackets is evaluated and its result is taken as the property name.

这篇关于在JSON.parse函数中传递外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆