简体   繁体   中英

what's the correct way of pulling from a JSON file with jQuery/plain JS?

Solved

Turns out I messed up my JSON while trying to fix it. Thanks for helping. Showed me some new methods to use json:)

I searched through a lot of other questions, tried the responses, some did something others just threw an error. If it worked, it logged this whole list of metadata (including the json data I want) to the console:

{…}
​
abort: function abort(e)​
always: function always()​
catch: function catch(e)​
done: function add()​
fail: function add()​
getAllResponseHeaders: function getAllResponseHeaders()​
getResponseHeader: function getResponseHeader(e)​
overrideMimeType: function overrideMimeType(e)​
pipe: function pipe()​
progress: function add()​
promise: function promise(e)
​
readyState: 4
​
responseText: "<JSON content>"
​
setRequestHeader: function setRequestHeader(e, t)​
state: function state()
​
status: 200
​
statusCode: function statusCode(e)
​
statusText: "OK"
​
then: function then(t, n, r)​
<prototype>: Object { … }

So, my question is: how do I get the json contents from this?

Code used:

function start() {
  var j = $.ajax({
    url: 'users.json',
    type: "GET",
    dataType: "json",
    success: function (data) {
      console.log(data);
    }
  });
}

Json:

        "UsersByID":[ {
                "id": 1
                "Name": ["K", "L", "Smiths"],
                "Birthday": ["03", "10", "1987"],
                "Username": "user1",
                "Password": "verysafepassword",
                "Hollidays": [{
                        "HollidayId": 1
                        "HollidayType": 2,
                        "AmountOfPeople": 5,
                        "Date": ["18", "08", "2020"]
                        }{
                        "HollidayId": 2
                        "HollidayType": 3,
                        "AmountOfPeople": 2,
                        "Date": ["24", "10", "2020"]
                        }

                }]

        }]
    }
}

What you normally do (in plain javascript) is to filter throughthe delivered JSON. Since I do not know what you want to filter, some pseudo code how it works:

   function start() {
     var j = $.ajax({
       url: 'users.json',
       type: "GET",
       dataType: "json",
       success: function (response) { //data is a keyword so better use response
         console.log(response);

        response.data.forEach(function(field) { // we iterate through each field in the JSON
         if (field.typeField == "UsersByID") {  // Given the JSON part looks like {"UsersByID":{"myBigData": "secrets","yourBigData": "noSecrets"}}
        console.info("My content found"); 
        // Do whatever you have to do with the content
        }
      }); // for each END

    }
  });
}

EDITT To process the JSON there are different posibilities If you know what is comming you filter like I have done above and then do something with the result.
Another way if you don't have to extract, but the whole response is the needed JSON you do as follows (and of course you can combine)

function start() {
     var j = $.ajax({
       url: 'users.json',
       type: "GET",
       dataType: "json",
       success: function (response) { //data is a keyword so better use response
         console.log(response);
         var myObj = JSON.parse(response);
        // Do whatever you have to do with myObj e.g.
       var u_username = myObj.Username; // you retrieve from the object with the field names
  // when nested you get a new object and then you retrieve
    var objHollidays = myObj.Hollidays;
    var u_HollidayId = objHollidays.HollidayId;
    // OR you iterate over all objHollidays 
    objHollidays.HollidayId.forEach(function(field) { // we iterate through each 
        //Do whatever you need
       });
    }
  });
} 

Parsing Dates
Date objects are not allowed in JSON.
If you need to include a date, write it as a string.
You can convert it back into a date object later:

 var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
 var obj = JSON.parse(text);
 obj.birth = new Date(obj.birth);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM