如何使用jQuery访问我的json文件中的这些键和值?

时间:2017-07-01 07:33:25

标签: javascript jquery json object

我无法访问json文件中的键和值。我已经尝试了很多东西但是我的注意力集中在本周并且我被卡住了。

这是我的transport.json文件..

{"transportation":[
    {"Springfield":[{
        "bus":[{
            "start": 6,
            "end": 24,
            "stops":["oak street", "main street"]
        }],
        "taxi":[{
            "start": 25,
            "end": 25,
            "stops":["all"]
        }]
    }]},
    {"Pleasantville":[{
        "bus":[{
            "start": 6,
            "end": 22,
            "stops":["centre street", "river street"]
        }],
        "taxi":[{
            "start": 25,
            "end": 25,
            "stops":["all"]
        }],
        "train":[{
            "start": 6,
            "end": 23,
            "stops":["uptown", "downtown"]
        }]
    }]}
]}

我要做的两件事是......

  1. 我希望能够提醒用户当前区域中的总线start值。

  2. 我想循环通过总线stops来与用户当前停止进行比较。

  3. 这是我的js代码..

    var currentArea = 'Pleasantville'; // this variable changes
    var currentStop = 'uptown'; // this variable changes
    $.getJSON("transport.json", function(jsontransportation) {
        $(jsontransportation.transportation).each(function(dataaaa) {
            var areaName = Object.keys(this);
            if (areaName == currentArea) { // this works to find correct area in json
                $(this.bus).each(function(key, value) { // i can't get this loop to work
                    alert(this.start); // alerts nothing, no errors
                    $(this.stops).each(function(key) { // now im trying to loop through keys in 'stops'
                        if (this.key === currentStop) { // to compare stop to current area
                            alert('the bus stops here at ' + currentStop); // and alert if there is a stop here
                        } else {
                            alert('the bus does not stop here at ' + currentStop); // else alert no stop here
                        }
                    })
                });
            }
        });
    });
    

4 个答案:

答案 0 :(得分:1)

你在不同的地方使用了错误的钥匙,实际上检查公交车是否停在用户的当前停车位,你不需要遍历所有车站并比较你可以使用indexOf(),代码应该工作:

var currentArea = 'Pleasantville'; // this variable changes
var currentStop = 'uptown'; // this variable changes
$.getJSON("transport.json", function(jsontransportation) {
    $(jsontransportation.transportation).each(function(dataaaa) {
        var areaName = Object.keys(this)[0];
        if (areaName == currentArea) { // this works to find correct area in json
        var selectedCityObject = this[areaName][0]
            $(selectedCityObject.bus).each(function(key, value) { // i can't get this loop to work
                alert(value.start); // alerts nothing, no errors
                if (value.stops.indexOf(currentStop) >= 0) { // to compare stop to current area
                        alert('the bus stops here at ' + currentStop); // and alert if there is a stop here
                    } else {
                        alert('the bus does not stop here at ' + currentStop); // else alert no stop here
                    }
            });
        }
    });
});

答案 1 :(得分:1)

试试这个:

@RepositoryRestController
@RequestMapping("/users")
public class UsersController
{
    @RequestMapping(value = "/hello/{variable}", method =   RequestMethod.GET)
    public @ResponseBody ResponseEntity<?> hello(@PathVariable String variable) throws Exception
    {
        if (variable.equals("1")) {
            throw new Exception("my exception");
        }
        else {
            return ok("hello world");
        }
    }

    @ExceptionHandler
    public String logErrors(Exception e) {
        return "error: " +e.getMessage();
    }
}

答案 2 :(得分:1)

这正是您所需要的。我还更改了代码,以便警报只显示一次。

$(document).ready(function(){
   var currentArea = 'Pleasantville'; // this variable changes
   var currentStop = 'uptown'; // this variable changes
  $.getJSON("transport.json", function(jsontransportation) {
      $(jsontransportation.transportation).each(function(dataaaa) {
          var areaName = Object.keys(this);
          if (areaName == currentArea) { 
             var selectedArea = this[currentArea];
             var bus = selectedArea[0].bus;
             var stops;
             $(bus).each(function(keyBus, valueBus) { 
               alert(this.start); 
               stops = false;
               $(this.stops).each(function(key, valueStops) { 
                      if (valueStops === currentStop) { 
                          stops = true;
                      } 
                  })
             });
             if(stops){
                alert('the bus stops here at ' + currentStop); 
             }else{
                alert('the bus does not stop here at ' + currentStop); // else alert no stop here
             }


          }
      });
  });
});

这里的解决方法是指向PLUNKR

的链接

答案 3 :(得分:0)

尝试更改serviceType以获取数据块。 (抱歉,没有jquery)

&#13;
&#13;
var $data = {
  "transportation": [{
      "Springfield": [{
        "bus": [{
          "start": 6,
          "end": 24,
          "stops": ["oak street", "main street"]
        }],
        "taxi": [{
          "start": 25,
          "end": 25,
          "stops": ["all"]
        }]
      }]
    },
    {
      "Pleasantville": [{
        "bus": [{
          "start": 6,
          "end": 22,
          "stops": ["centre street", "river street"]
        }],
        "taxi": [{
          "start": 25,
          "end": 25,
          "stops": ["all"]
        }],
        "train": [{
          "start": 6,
          "end": 23,
          "stops": ["uptown", "downtown"]
        }]
      }]
    }
  ]
};

var search = function(currentArea, currentStop, serviceType, callback) {
  var found = false;
  $data.transportation.forEach(function(area) {
    var $transport = area[currentArea];
    if ($transport) {
      $transport.forEach(function($types) {
        $service = $types[serviceType];
        if ($service) {
          $service.forEach(function($details) {
            if ($details.stops.indexOf(currentStop) > -1) {
              found = $details;
            }
          });
        }
      });
    }
  });

  setTimeout(function() {
    callback(found, currentArea, currentStop, serviceType);
  }, 0);
};

function response(data, currentArea, currentStop, serviceType) {
  if (data === false) {
    alert("The " + serviceType + " doesn't stop at " + currentStop + " for " + currentArea);
  } else {
    alert(serviceType + " starts at " + data.start + " at " + currentStop + ", " + currentArea);
  }
}

var currentArea = 'Pleasantville';
var currentStop = 'uptown';

search(currentArea, currentStop, 'bus', response);
search(currentArea, currentStop, 'train', response);
search(currentArea, 'river street', 'bus', response);
search('Springfield', 'oak street', 'bus', response);
&#13;
&#13;
&#13;