jQuery getJSON from API how to access object? - javascript

I am trying to get JSON from API and then access "main" object of the "weather" object of the JSON.
When I use this code:
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
var data = JSON.stringify(json);
alert(data);
});
I get this output:
{
"coord": {
"lon": 159,
"lat": 35
},
"weather": [{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "https://cdn.glitch.com/6e8889e5-7a72-48f0-a061-863548450de5%2F10n.png?1499366021399"
}],
"base": "stations",
"main": {
"temp": 22.59,
"pressure": 1027.45,
"humidity": 100,
"temp_min": 22.59,
"temp_max": 22.59,
"sea_level": 1027.47,
"grnd_level": 1027.45
},
"wind": {
"speed": 8.12,
"deg": 246.503
},
"rain": {
"3h": 0.45
},
"clouds": {
"all": 92
},
"dt": 1499521932,
"sys": {
"message": 0.0034,
"sunrise": 1499451436,
"sunset": 1499503246
},
"id": 0,
"name": "",
"cod": 200
}
Now, the output that I am trying to get is "Rain" (the property of the "main" object of the "weather" object (I hope I said this correctly, I'm a beginner)).
So logically, I would do this:
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
var data = JSON.stringify(json);
alert(data["weather"].main);
});
But that doesn't give me any output.
I did some search, and found out that I should parse.
But when I did:
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json) {
var data = JSON.stringify(json);
var Jason = JSON.parse(data);
alert(Jason["weather"].main);
});
I got undefined as my output again.
So, what should my code look like so my output would be "Rain"?
PS: Sorry if I made mistakes in describing my issue, I am really new to JavaScript/jQuery and also English is my second language.

You nearly have it, simply add [0] after accessing the weather.
Since weather is an Array, you need this to get the data from the first element:
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139",
json => console.log(json.weather[0].main)
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Also, the getJSON function already parses the JSON for you, no need for additional JSON.parses

JSON.Stringify will convert json to string. If you want to access objects, you need JSON object and not string.
weather is an array of objects and you need to access an array using index. As you want 1st object, use json["weather"][0]
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139", function(json){
alert(json["weather"][0].main);
});

Related

Destructuring a json object in Javascript

How would access the _id and state values?
Here's the data
{
"data": {
"totalSamplesTested": "578841",
"totalConfirmedCases": 61307,
"totalActiveCases": 3627,
"discharged": 56557,
"death": 1123,
"states": [
{
"state": "Lagos",
"_id": "O3F8Nr2qg",
"confirmedCases": 20555,
"casesOnAdmission": 934,
"discharged": 19414,
"death": 207
},
{
"state": "FCT",
"_id": "QFlGp4md3y",
"confirmedCases": 5910,
"casesOnAdmission": 542,
"discharged": 5289,
"death": 79
}
]
}
}
What you have shown is a string in JSON format. You can convert that to a JavaScript object and then start to get the values you need from it.
let str = ‘{
"data": {
"totalSamplesTested": "578841",
"totalConfirmedCases": 61307,
"totalActiveCases": 3627,
"discharged": 56557,
"death": 1123,
"states": [
{
"state": "Lagos",
"_id": "O3F8Nr2qg",
"confirmedCases": 20555,
"casesOnAdmission": 934,
"discharged": 19414,
"death": 207
},
{
"state": "FCT",
"_id": "QFlGp4md3y",
"confirmedCases": 5910,
"casesOnAdmission": 542,
"discharged": 5289,
"death": 79
}
]
}
} ‘;
(Note, I have put the string in single quotes so it can be shown properly here but in your code you need to put it in back ticks so it can span many lines)
Now convert it to a JavaScript object.
let obj = JSON.parse(str);
Now look closely at the string to see how the object is structured. It actually has just one item in it, data. And that is itself an object with several items, one of which is states which is an array.
So, obj.data.states[0] is the array’s first entry. That is an object and has _id and state items.
You can step through the array extracting the ._id and .state entries.

How to Get key value from parseJson()

I have a case that is how to find the value of a key that is in sekrip as follows:
JSON.parse({
"data": [
{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}
]
});
The above data was obtained from:
<script type='text/javascript' src='http://domain.com/target.php'></script>
I want to get the value of the key "id_user", anyone can help me?
Thanks before.
Several issues here. Firstly, the method you're looking for is JSON.parse(), not parseJSON. Secondly, what you're providing to that function is already an object, not a JSON string, therefore it doesn't need to be deserialised as you can access it as you would any normal object:
var obj = {
"data": [{
"id_user": "351023",
"name": "",
"age": "29",
"link": "http://domain.com"
}]
}
console.log(obj.data[0].id_user);
First its JSON.parse. Second it needs to be a JSON string.
Fiddle: http://jsfiddle.net/5m5qs1x4/
var jsonData = JSON.parse('{"data": [{"id_user": "351023","name": "","age": "29","link": "http://domain.com"}]}');
document.getElementById('test').textContent = jsonData.data[0].id_user;
You need to parse JSON string and than, access to keys/index
var data = JSON.parse("{\"data\": [{ \"id_user\": \"351023\",\"name\": \"\",\"age\": \"29\",\"link\": \"http://domain.com\"}]}");
document.write(data["data"][0]["id_user"]);

javascript retrieve value from json

How to get value from [object Object] in javaScript.
i have a json response from php which i pass in javascript .
i want GPSPoint_lat,GPSPoint_lon all value.
var jArray = ;
var obj = JSON.parse(jArray);
i got [object Object] how i retrive the all value from obj.
my json string is-
{
"Account": "dimts",
"Account_desc": "Adminstrator",
"TimeZone": "Asia/Calcutta",
"DeviceList": [
{
"Device": "dl1pb1831",
"Device_desc": "DL 1PB 1831",
"EventData": [
{
"Device": "dl1pb1831",
"Timestamp": 1387790572,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:52",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.52802,77.14041",
"GPSPoint_lat": 28.52802,
"GPSPoint_lon": 77.14041,
"Speed": 12.9,
"Speed_units": "km/h",
"Heading": 193.6,
"Heading_desc": "S",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
{
"Device": "dl1pb7520",
"Device_desc": "DL 1PB 7520",
"EventData": [
{
"Device": "dl1pb7520",
"Timestamp": 1387790574,
"Timestamp_date": "2013/12/23",
"Timestamp_time": "14:52:54",
"StatusCode": 61472,
"StatusCode_hex": "0xF020",
"StatusCode_desc": "Location",
"GPSPoint": "28.56589,77.05268",
"GPSPoint_lat": 28.56589,
"GPSPoint_lon": 77.05268,
"Speed": 29.9,
"Speed_units": "km/h",
"Heading": 91.4,
"Heading_desc": "E",
"DigitalInputMask": 3,
"DigitalInputMask_hex": "0x03",
"Index": 0
}
]
},
Look at javascript tutorial
obj['key_name']
JSON objects work as an array. You can access to an element with a key:
obj['Account'] // returns dimts
obj.Account // works also
You should read some tutorial about it, like JSON: What It Is, How It Works, & How to Use It
Please retrive the value as
var jArray = <?php echo json_encode($_SESSION['return'] ); ?>;
var obj = JSON.parse(jArray);
var value=obj.Result;
I have zero experience in php so I don't know what's the resulting object from your first line of code. But assuming jArray is a json object with the structure defined in your question...you access its values as shown below...
jArray.Account;
jArray.DeviceList[0].Device; //access the device property of the first object in the DeviceList array
jArray.DeciveList[0].EventData.StatusCode;

Create an object dynamically from JSON

Can I create an object dynamically from JSON?
This is one of some in array:
values: [{
"$type": "Entrance, DataModel",
"EntranceDeviceData": {
"$type": "DeviceData, DataModel",
"Watchdog": 0,
"Inputs": {
"$type": "Int16[], mscorlib",
"$values": [0, 0]
},
"Outputs": {
"$type": "Int16[], mscorlib",
"$values": [0, 0]
},
"Faults": {
"$type": "Int16[], mscorlib",
"$values": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
"StandingCommand": 0
},
"Vehicle": null,
"NextStates": {
"$type": "System.Collections.Generic.List`1[[System.String, mscorlib]], mscorlib",
"$values": ["CarApproachingBarrier"]
},
"Repository": {
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"
},
"Direction": 0,
"Name": "Entrance",
"Position": "0,0,0,0",
}, {...another object...
}, {...another one...
}
]
This both JSON objects are different. Can I create an object (for every other JSON object) without knowing in advance it's properties? How can I do it?
(I heard something that it possible, but maybe I didn't understand well the person who said that).
What you gave as examples of JSON in your original code above is Javascript's way of defining literal objects. json1 and json2 already ARE javascript objects, no need to create them.
// original code from question
var json1 = {
"mysex": "female",
"yoursex": "male",
"location": {
"lat": "48",
"lng": "1"
},
"description": "descr2",
"owner": "zBYnfuu8DXEwMttwZ",
"nickname": "user",
"_id": "1"
};
As nnnnnn pointed out below JSON is most commonly used to refer to a STRING containing code formatted as above, that would be:
var json1_as_string = '{
"mysex": "female",
"yoursex": "male",
"location": {
"lat": "48",
"lng": "1"
},
"description": "descr2",
"owner": "zBYnfuu8DXEwMttwZ",
"nickname": "user",
"_id": "1"
}';
To get from such a String to an actual Javascript Object you would need to parse it:
var json1 = JSON.parse(json1_as_string);
the opposite direction (Javascript Object to String) is achieved by stringify:
var json1_as_string = JSON.stringify(json1);
see https://developer.mozilla.org/en-US/docs/Using_native_JSON
p.s.
It does seem strange that these two very different objects have the same "_id".
You've changed the question completely, and I'm trying to understand what you are asking.
This both JSON objects are different. Can I create an object (for
every other JSON object) without knowing in advance it's properties?
How can I do it?
Yes, in Javascript you can create objects without knowing their properties in advance. Javascript is not strongly typed, and it has no classes. So there's absolutely no problem
with having objects with different properties.

Parsing JSON with jQuery, retrieving two variables.

I have a online JSON file that looks something like this:
[
{
"j": 0,
"i": 0,
"DepartureTime": "\/Date(1331667480000+0100)\/",
"ArrivalTime": "\/Date(1331668860000+0100)\/",
"Remarks": [],
"TravelStages": [
{
"ID": 0,
"DepartureStop": {
"WalkingDistance": 0,
"ArrivalTime": null,
"AlightingAllowed": false,
"DepartureTime": null,
"BoardingAllowed": false,
"RealTimeStop": true,
"Rank": 0,
"Lines": null,
"StopPoints": [
{
"ID": 1,
"Name": "1",
"X": 608127,
"Y": 6645778
}
],
"Zone": "1",
"X": 608133,
"Y": 6645768,
"ID": 2300500,
"Name": "Visperud (i Solheimvn)",
"District": "Lørenskog",
"Type": 0,
"Stops": [],
"ShortName": "VIS"
}]
What I want is the grab out the DepartureTime and ArrivalTime, I've seen some examples on how to parse the flickr JSON. But I can't figure out how I can parse this. I also want to store the departureTime and arrivalTime in two separate variables since the content of this two is a time measured in milliseconds since 1970. Can somebody give me a hint on how a can do this, am totally new to Javascript/JSON
Do you have jQuery in your project? If so, you can easily parse the JSON string like this
var obj = $.parseJSON(theJsonText);
alert(obj.DepartureTime);
If not, I suggest including the JSON library (link) and using that.
You can try something like this, assuming that your json file is in jsonfile.json
$.getJSON('jsonfile.json', function(data){
alert("Departure Time: "+ data.DepartureTime);
alert("Arrival Time: "+ data.ArrivalTime);
});
http://api.jquery.com/jQuery.getJSON/
$.getJSON('http://your.domain.example/path/to/file.json', function(data) {
departure_time=data.DepartureTime;
arrival_time=data.ArrivalTime;
do_something_with(departure_time,arrival_time);
});
then do_something_with(str,str) would be called with the strings "\/Date(1331667480000+0100)\/" and "\/Date(1331668860000+0100)\/" (in your example).
you'll still have to convert the dates to numbers, e.g. by running:
parsed_date=new Date(parseInt(input_string.substr(7)));
//substr(7) cuts after "\/Date(", and parseInt ignores ")\/"
//but I don't know how it handles "+0100"
Thats an array containing objects, so you should be able to just set some vars equal to the properties of the first index. to use it like an object, it needs to be parsed.. so either eval(thatJson) or $.parseJSON(thatJson) and then iterate through it.
var responses = [
{
"j": 0,
"i": 0,
"DepartureTime": "\/Date(1331667480000+0100)\/",
"ArrivalTime": "\/Date(1331668860000+0100)\/",
"Remarks": [],
...
}];
var dep = responses[0].DepartureTime;
var arr = responses[0].ArrivalTime;
According to JSONLint.com, your string isn't valid JSON. That is, however, a different issue than what your question asks for.
Assuming a valid subset of your string
var a = '[{"j": 0,"i": 0,"DepartureTime": "/Date(1331667480000+0100)/", "ArrivalTime": "/Date(1331668860000+0100)/","Remarks": []}]';
var obj = $.parseJSON(a);
console.log(obj[0].ArrivalTime);​

Categories

Resources