Javascript 从json中的动态键值获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3863198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get data from dynamic key value in json
提问by AutoMEta
The requirement is following:
I have to get the location field from page.
要求如下:
我必须从页面中获取位置字段。
var input= global.input = document.getElementById("Location");
Get the neighborhood area from the json file based on input and show on the page.
根据输入从json文件中获取邻域区域并显示在页面上。
I have a json object and have to filter the data from the json object based on the key value (location)
我有一个 json 对象,必须根据键值(位置)过滤来自 json 对象的数据
var inputLocation=input.value;
In my javascript I am getting the error if I use dynamic the key.
在我的 javascript 中,如果我使用动态密钥,我会收到错误消息。
I am able to get the json array if I do this data.Aspen
but i have to get the data from a text field and it can be different so if I call data.inputLocation... its coming undefined
如果我这样做,我可以获得 json 数组,data.Aspen
但我必须从文本字段中获取数据,它可能会有所不同,所以如果我调用 data.inputLocation...它即将到来
when i use data.(inputLocation.value)
getting the following error :
当我使用时data.(inputLocation.value)
出现以下错误:
XML filter is applied to non-XML value ({Aspen:[{ID:
XML 过滤器应用于非 XML 值 ({Aspen:[{ID:
{
"Aspen":[
{
"ID":"Bellaire",
"Name":"Bellaire"
},
{
"ID":"Champions Forest",
"Name":"Champions Forest"
},
{
"ID":"Highland Village",
"Name":"Highland Village"
},
{
"ID":"Museum District",
"Name":"Museum District"
}
]
}
回答by Douglas
You can access the property using the array-like syntax:
您可以使用类似数组的语法访问该属性:
data[inputLocation]
If inputLocation
is set to "Aspen"
, this it is the same as these two lines:
如果inputLocation
设置为"Aspen"
,则与这两行相同:
data["Aspen"]
data.Aspen
回答by Yasin Sunni
get value from dynamic json object Using real time currency converter rest api responce
从动态 json 对象中获取价值使用实时货币转换器 rest api 响应
public async Task<JsonResult> ConvertCurrency(float Price, string FromCurrency)
{
var testcase = FromCurrency + "_USD";
WebClient web = new WebClient();
const string ConverterApiURL = "http://free.currencyconverterapi.com/api/v5/convert?q={0}_{1}&compact=ultra&apiKey={{EnterKey}}";
string url = String.Format(ConverterApiURL, FromCurrency, "USD");
string response = new WebClient().DownloadString(url);
var data = (JObject)JsonConvert.DeserializeObject(response);
dynamic result = data.SelectToken(testcase + ".val").ToString();
var basePrice = float.Parse(result);
double exchangeRate = Price * basePrice;
var responce = Math.Round(exchangeRate, 2);
return Json(responce, JsonRequestBehavior.AllowGet);
}