获得一个JSON值与另一个?

时间:2017-04-30 09:14:09

标签: javascript jquery json

我有这个JSON字符串:

Iterator<Map<String, Integer>> iter = set.iterator();
while (iter.hasNext ()) {
    Map<String, Integer> map = iter.next();
    for (String str : map.keySet()){
        if (some condition) {
            iter.remove();
            break; // you should probably break from the inner loop
                   // after removing an element
        } else {
            //System.out.println("test");
        }
    }
}

我想要做的就是找到x值(它等于1或者什么。)然后找到旁边的y值。 我怎么能这样做?

我想用JavaScript做这件事

2 个答案:

答案 0 :(得分:0)

解析它并迭代它

var data = JSON.parse('{"XXX":{"x":"1","y":"2"},"XXX":{"x":"3","y":"3"}}');

var y = 0;
$.each(data, function(i, item) {
    alert('With Jquery X = '+item.x);
    alert('With Jquery Y = '+item.y);
    //if you want to get the value of y based on x or vice versa then check
    if(item.x == 3) {
       y = item.y;
    }   
 });
    // Then you can use the value of y here.
    alert('This is the matching Y = '+ y);
    
    
    
    
    // With Plain Js
    for(key in data) {
  alert( 'With Plain JS X = '+data[key].x );
    alert( 'With Plain JS Y = '+data[key].y );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

使用Json解析。

一个简单的例子:

var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
document.getElementById("demo1").innerHTML =
obj.employees[2].firstName + " " + obj.employees[2].lastName;
document.getElementById("demo2").innerHTML =
obj.employees[1].firstName + " " + obj.employees[2].lastName;
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>