How to handle JSON like response in javascript?
How to read JSON(server response) in Javascript? - Stack Overflow
What exactly does response.json() do?
JavaScript fetch API - Why does response.json() return a promise object (instead of JSON)? - Stack Overflow
Videos
If you're trying to use JSON format, your problem is that the data within the [...] also needs to be in pairs, and grouped in {...} like here.
For instance,
{
"sales": [
{ "firstname" : "John", "lastname" : "Brown" },
{ "firstname" : "Marc", "lastname" : "Johnson" }
] // end of sales array
}
So you might have:
{"COLUMNS": [
{"REGISTRATION_DT" : "19901212", "USERNAME" : "kudos", "PASSWORD" : "tx91!#1", ... },
{"REGISTRATION_DT" : "19940709", "USERNAME" : "jenny", "PASSWORD" : "fxuf#2", ... },
{"REGISTRATION_DT" : "20070110", "USERNAME" : "benji12", "PASSWORD" : "rabbit19", ... }
]
}
If the server is sending you something which you refer to as res, you can just do this to parse it in your Javascript:
var o=JSON.parse(res);
You can then cycle through each instance within columns like follows:
for (var i=0;i<o.COLUMNS.length;i++)
{
var date = o.COLUMNS[i].REGISTRATION_DT; ....
}
Please take a look on example code snippet as shown below
Example JSON
{
"name": "mkyong",
"age": 30,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
Here is the code to read the json
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York
alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax
alert(json.phoneNumber.number); //undefined
Code:
fetch('http://api-to-call.com/endpoint').then(response => {
if (response.ok) {
return response.json();
}
else {
throw new Error('Request failed!');
}
}, networkError => console.log(networkError.message)
).then(jsonResponse => {
console.log(jsonResponse)
});From my current understanding, the first .then() returns a promise that resolves to response.json(). However, after reading up on it a little bit, it seems response.json() returns a promise itself. So it's a promise within a promise?
Also, reponse.json() converts a response object to JSON too? I don't get it.
I'd greatly appreciate some clarity on this
I'm working on an Express API, and I was curious what the current consensus is on JSON formats for API requests and responses? I've been using Google's JSON style guide, which I've enjoyed. Do you all have preferences? Are there pitfalls to watch out for?