为一个输出解析JSON多维数据

时间:2017-09-12 19:30:56

标签: jquery json parsing

我试图通过JQuery解析这些数据:

http://www.mycurrency.net/service/rates

我想搜索一下,找到一个匹配的国家/地区代码,我将其存储在名为' code'的变量中。然后返回该国家的费率。

对不起,如果这是重复的,我已经查看了答案,它们太复杂或太简单。

4 个答案:

答案 0 :(得分:1)



var json = '[{"currency_code":"AED","rate":3.6727,"code":"AE","name":"United Arab Emirates"},{"currency_code":"AFN","rate":68.51,"code":"AF","name":"Afghanistan"},{"currency_code":"ALL","rate":111.55,"code":"AL","name":"Albania"},{"currency_code":"AMD","rate":477.85,"code":"AM","name":"Armenia"},{"currency_code":"ANG","rate":1.7775,"code":"AW","name":"Aruba"},{"currency_code":"AOA","rate":165.096,"code":"AO","name":"Angola"}]'
var Code="AW";
$.each(jQuery.parseJSON(json),function(key,value){
  if(value.code==Code)
   $("body").append("<span> "+value.currency_code+" |</span><span> "+value.rate+" |</span><span> "+value.code+" |</span><span> "+value.name+" </span><hr>");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Var Code ;  
var Result = new FromData();
 $.each(yourjsonfile, function (key, value) {
        if (youjsonfile.Code = Code)
Result.append(key, value);
    });

我没有太多经验,我也不能发表评论,但你试过这个吗? 这将循环你数据比较代码并将其附加到formdata var然后你可以通过ajax发布它

答案 2 :(得分:0)

请参阅以下代码。希望有所帮助。您可以在对象数组中获取数据,然后应用map和reduce来查找所需的键。我刚刚从URL复制了样本数据并准备了这个小片段。

&#13;
&#13;
data = [{
  "currency_code": "AED",
  "rate": 3.6727,
  "code": "AE",
  "name": "United Arab Emirates"
}, {
  "currency_code": "AFN",
  "rate": 68.4958,
  "code": "AF",
  "name": "Afghanistan"
}, {
  "currency_code": "ALL",
  "rate": 111.5,
  "code": "AL",
  "name": "Albania"
}, {
  "currency_code": "AMD",
  "rate": 477.85,
  "code": "AM",
  "name": "Armenia"
}, {
  "currency_code": "ANG",
  "rate": 1.7775,
  "code": "AW",
  "name": "Aruba"
}, {
  "currency_code": "AOA",
  "rate": 165.096,
  "code": "AO",
  "name": "Angola"
}];


code = 'AE';
arr = [];

arr = data.map(function(e) {
  if (e.code == code)
    return e.rate;
}).reduce(function(accumulator, value) {

  if (value == undefined)
    return accumulator;
  else
    return value;
});


console.log(arr);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个小提琴https://jsfiddle.net/sq8vfx0x/1/

<p class="code"></div>
<p class="rate"></div>

var o = [
{"currency_code":"AED","rate":3.6727,"code":"AE","name":"United Arab Emirates"},
{"currency_code":"AFN","rate":68.5003,"code":"AF","name":"Afghanistan"},
{"currency_code":"ALL","rate":111.479,"code":"AL","name":"Albania"},
{"currency_code":"AMD","rate":477.85,"code":"AM","name":"Armenia"}
];

var searchCode = 'AF';
var code;
for(var x = 0; x < o.length; x++){
    if(o[x].code == searchCode){
        code = o[x].code;
        $('.rate').append('<p>' + o[x].rate + '</p>');
    }
}
$('.code').append('<p>' + code + '</p>');