[英]Turn a json object string into value
I am writing a function that takes a string, splits it, and the uses json[key][key2][key3]
formatting. 我正在编写一个函数,该函数需要一个字符串,将其拆分,然后使用json[key][key2][key3]
格式化。 The problem is n is potentially infinite (not literally but needs to written that way) 问题是n可能是无限的(不是字面意义,而是需要这样写)
function getJsonValue(json,string) {
var vals = string.split(".");
var x = vals.length;
var string = '';
while (x != 0) {
string += "['"+vals[(vals.length-x)]+"']"
x--
}
return string;
}
That will produce, for example: "['condition']['item']['condition']['temp']"
这样会产生例如: "['condition']['item']['condition']['temp']"
I need to extract a value from that by attaching it to a json object, like 我需要通过将值附加到json对象来从中提取值,例如
json"['condition']['item']['condition']['temp']"
But I don't know how or if that is even possible. 但是我不知道怎么做到,甚至可能。
Edit: The problem is I need any value from a config file to be passed in and then parsed from a returning function. 编辑:问题是我需要从配置文件中传入任何值,然后从返回的函数中进行解析。 Ie User knows the value will be condition.item.condition.temp for this specific query. 即,用户知道该特定查询的值将为condition.item.condition.temp。 I am trying to write one function that covers everything and pass in config values for what I know to be the output. 我正在尝试编写一个涵盖所有内容的函数,并为我知道的输出传递配置值。 So, on one query, I might want the condition.item.condition.temp value and on another I might want condition.wind.chill . 因此,在一个查询中,我可能需要condition.item.condition.temp值,在另一个查询中,我可能想要condition.wind.chill。
I'm not sure if I understand 100% what you're trying to do, but if you're receiving a JS object json
and a string in the format field1.field2.field3
and trying to get the value of json.field1.field2.field3
then you can do something like this: 我不确定我是否100%理解您要尝试执行的操作,但是如果您收到JS对象json
和格式为field1.field2.field3
的字符串,并尝试获取json.field1.field2.field3
的值json.field1.field2.field3
那么您可以执行以下操作:
function getJsonValue(json,string) {
var vals = string.split(".");
for (var i = 0; i < vals.length; i++) json = json[vals[i]];
return json;
}
It would work like this for a given object: 对于给定的对象,它将像这样工作:
var obj = { field1: { field2: { field3: "Hello!" } } };
var res = getJsonValue(obj, "field1.field2.field3");
console.log(res); // prints Hello
What about doing an eval? 进行评估如何?
var json = {
'one': {
'two': {
'three': {
'four': 4
}
}
}
};
alert(eval("json['one']['two']['three']['four']"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.