簡體   English   中英

從json中的動態鍵值獲取數據

[英]get data from dynamic key value in json

要求如下:
我必須從頁面中獲取位置字段。

var input= global.input = document.getElementById("Location");

根據輸入從json文件中獲取鄰域區域並顯示在頁面上。

我有一個 json 對象,必須根據鍵值(位置)從 json 對象中過濾數據

var inputLocation=input.value;

在我的 javascript 中,如果我使用動態密鑰,我會收到錯誤消息。

如果我執行此data.Aspen ,我能夠獲得 json 數組,但我必須從文本字段中獲取數據,並且它可能會有所不同,因此如果我調用 data.inputLocation ......它即將到來

當我使用data.(inputLocation.value)出現以下錯誤:

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"
 }
 ]
}

您可以使用類似數組的語法訪問該屬性:

data[inputLocation]

如果inputLocation設置為"Aspen" ,則與這兩行相同:

data["Aspen"]
data.Aspen

從動態 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM