Parse JSON data from API - javascript

I am new to working with Jquery JSON and API's(this being my first Stack question, so please bear with me). So I am trying to figure out a way in which Im hitting a API and it will return data(city name) in JSON which I have to display on my page in list form. But the cities should be updated and the page should display the city names dynamically.
Here is the fiddle link:
Fiddle File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST2</title>
</head>
<body>
<button>Submit</button>
<select id="list"></select>
</body>
</html>
<script type="text/javscript" src="jquery-3.1.0.js"></script>
<script type="text/javscript">
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('list', {
text: element.detail
}));
});
}
});
</script>
JSON FILE
[
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]
Requesting for your help, thanks in advance for those who contributed

Provided you receive data from API you can do what you want.
//...
success: function (data) {
$.each(data, function(index, element) {
//$('body').append($('list', {//no comment
// text: element.detail
//}));
//add cities to select id="list"
$('<option/>') //create option
.val(element.id) //set its value
.text(element.detail) //set text
.appendTo('#list'); //and append to the list
});//each
}

this is not a JSON object, its an array, are you sure it comes back like this? try to log it then do one of the following:
if it comes as a string write this
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
accepts: "application/json; charset=utf-8"
/* ... */
the accepts tells the server to send back json, hence you can get it as json. if it is still a string, write JSON.parse(data)
if it comes as an array like youve written, then there should be no problem, except that its an array not a json object. json should be an object not an array.
{results: [
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]}
something like this will make it a json file.
if it comes like this, then you should write: data.results to access the array you need.

You don't need to parse. JSON is JavaScript Object Notation. you can just asign data to variable and use it in your code like
success: function(result) {
var data = result;
data.forEach(function(data){
$('body').append($('list', {
text: element.detail
}));
}
console.log(data);
//in console you can see tyour data
Object {type: "form-focus", element: "#run"}

Related

How to call this data piece in Ajax?

I would like to call the meters (732) piece of data from the following json API return:
{"results":1,"data":[{"wind":{"degrees":200,"speed_kts":6,"speed_mph":7,"speed_mps":3,"speed_kph":11},"temperature":{"celsius":16,"fahrenheit":61},"dewpoint":{"celsius":14,"fahrenheit":57},"humidity":{"percent":88},"barometer":{"hg":30.06,"hpa":1018,"kpa":101.79,"mb":1017.92},"visibility":{"miles":"Greater than 6","miles_float":6.21,"meters":"10,000+","meters_float":10000},"ceiling":{"code":"BKN","text":"Broken","feet":2400,"meters":732,"base_feet_agl":2400,"base_meters_agl":732},"elevation":{"feet":256,"meters":78},"location":{"coordinates":[-2.27495,53.353699],"type":"Point"},"icao":"EGCC","station":{"name":"Manchester Airport"},"observed":"2020-07-18T00:50:00.000Z","raw_text":"EGCC 180050Z AUTO 20006KT 9999 BKN024 16/14 Q1018","flight_category":"MVFR","clouds":[{"code":"BKN","text":"Broken","feet":2400,"meters":732,"base_feet_agl":2400,"base_meters_agl":732}],"conditions":[]}]}
This code doesn't seem to call it:
jQuery.ajax({
type: 'GET',
url: 'https://api.checkwx.com/metar/EGCC/decoded',
headers: { 'X-API-Key': 'apikey' },
dataType: 'json',
success: function(data) {
console.log(data)
var ceiling = data.ceiling.feet;
jQuery('#a53feet').html( ceiling );
}
});
Html:
<span id="a53feet"></span>
Is it something in the call pathway (data.ceiling.feet), that isn't right?
The json returned is an array you need to use like below
For accessing feet data
data.data[0].ceiling.feet;
For accessing meters data
data.data[0].ceiling.meters
If you see the console.log, data is an object which has data as an array , so for access the data that you are trying to , you need to do something like below:
data.data[0].ceiling.meters

JSON data in array

I am absolut beginner level of web development. I would like to ask how to handle the json data from that link https://www.maxenergy.com.mm/api/max_price_list. I want to show the Diesel price in my page. But how to select the exact key form json data.
[
{
"Ayeyarwady":[
{
"price":{
"95 Ron Octane":660.00,
"Premium Diesel":620.00,
"Diesel":580.00,
"92 Ron Octane":580.00
},
"address":"Aungsan Road, Yay Kyi Township,Ayeyarwady.",
"station":"Max Energy (Yay Kyi)",
"longitude":null,
"latitude":null,
"telephone":"09977877901, 046-52020"
},
{ },
{ },
{ },
{ },
{ }
]
},
{ },
{ },
{ },
{ },
{ }
]
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="aya"></div>
<script>
$(document).ready(function() {
$.ajax({
url: 'https://www.maxenergy.com.mm/api/max_price_list',
dataType: 'jsonp',
type: 'GET',
}).done(function(data) {
$("#aya").html(data.Ayeyarwady.price.Diesel);
});
});
</script>
</body>
</html>
JSONArray json = new JSONArray(YOUR_RESPONSE);
for(int i=0;i<json.length();i++){
JSONObject dataJsonObject = new JSONObject(json.getJSONObject(i));
//FIRST JSONOBJECT
//NOW FROM THIS GET JSONARRAY Ayeyarwady
//AND MAKE IT FRO LOOP AGAIN AND get price and address like...
}
Hope this helps...
the array displayed in your page is part JSON part array (you can tell by the brackets type - [] is array, {} is JSON.
so you should use data[0].Ayeyarwady[0].price.Diesel (data and Ayeyarwady are arrays of objects with one child)
BUT this particular API isn't really supporting jsonp, and that's why it isn't working for you, if you add an error function callback you'll see that jQuery throws a parsererror on the data received.
you'll have to create a proxy server side request to the API, grab the data, parse as JSON and then get that data locally
Please change dataType like this,
dataType: 'json',

how to populate the json data in select dropdown using ajax?

Actually i need to display the list of school in a dropdown using select tag so far i am getting the response through hard coded values now here is the problem not able to generate through a link i am getting the data from rest full service how to do that , any on please help
<html>
<head>
<meta http-equiv="content-type" content="application/json; charset=UTF-8">
</head>
<body>
<select id="sel"></select>
<script>
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
</script>
</body>
</html>
You can use the getJSON method of jQuery
$('#brand').change(function(){
$.getJSON(
'your url to get json string',
'get parameters to send if any',
function(result){
//result would have your json string
//Empty the dropdown if it is having some items
$('#item').empty();
//Looping through all the json items
$.each(result.result, function(){
//Appending the json items to the dropdown (select tag)
//item is the id of your select tag
$('#item').append('<option>'+this['item']+'</option>');
});
});
});
Try this,
$(document).ready(function(){
getschool(val);
});
function getschool(val) {
$.ajax({
type: "GET",
url: 'http://localhost:8080/SMWS/Rest/parentService/parent/getSchoolDetails',
contentType: "application/json;charset=utf-8",
dataType: "json",
data:'school_id='+val,
success: function(data){
var html = '';
$.each(data, function(index,value){
html+= '<option value="'+value['item_value']+'">'+value['item']+'</option>';
});
$('#country-list').html(html);
}
});
}

Trouble receiving JSON data from nodejs application?

The below jQuery ajax method makes a call to node.js application that returns a json formatted data. I did check the console and it returns the json in this format
{ "SQLDB_ASSIGNED": 607, "SQLDB_POOLED":285, "SQLDB_RELEVANT":892, "SQLDB_TOTSERVERS":19}
However, when i try to access the element using the key name i get "undefined" on the console ?
Nodejs
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Jquery Ajax
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
for(var i in data)
{
console.log(data[i].SQLDB_ASSIGNED+"---"+data[i].SQLDB_POOLED+"---"+data[i].SQLDB_RELEVANT+"---"+data[i].SQLDB_TOTSERVERS );
}
}
});
Your Node.js part is very weird. You are stringifying a string:
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Why not just this? That's probably what you are looking for:
res.send(JSON.stringify({
SQLDB_ASSIGNED: assigned_tot,
SQLDB_POOLED: pooled_tot,
SQLDB_RELEVANT: relevant_tot,
SQLDB_TOTSERVERS: servertotal
}));
And then in the callback just this:
data.SQLDB_ASSIGNED; // Here you go
I don't know why you are iterating over the keys of the json. You want this:
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
So the code would be:
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
}
});
You seem to be treating the data variable as an array of objects, containing the keys you specify. I guess what you would like to do is this:
for(var key in data) {
console.log(key+": "+data[key]);
}
Or what?

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

Categories

Resources