javascript retrieve value from json - javascript

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;

Related

How do i access my json array with key named "data" in javascript?

I have json response returned from a rest api as below
{
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
I use jsonparse to convert it into object in javascript as below
var obj = JSON.parse(e.data)
When i access obj.extra.message it prints "Hello".
But when i try to access obj.data[0] , i get [object][Object] ,
seems like its taking "data" as a keyword?
How can i overcome this?
Note that you have your object inside an array.
Javascript doesn't show the whole object; you must use object's keys to access its data.
Obj.data[0] is the whole object.
It seems that your response is already JSON. So don't parse it again:
const data = {
"data":[
{
"id":"86",
"name":"Hello",
"last_name":"world"
}
],
"extra":{
"message":"Hello",
"additionalmessage":"world"
}
}
console.log(data["data"][0].name);
The parsing is working just fine; it's just that when you output the first element, you're just outputting the object, not one of its properties. The default toString on an object outputs [object Object]
You can try this:
var user = obj['data'][0];
console.log(user.name);
console.log(user.last_name);
Or try
JSON.stingify(obj.data[0])
here's how you can do it:
var obj = {
"data": [{ "id": "86", "name": "Hello", "last_name": "world" }],
"extra": { "message": "Hello", "additionalmessage": "world" }
};
console.log(obj["data"][0]["id"]);

jQuery getJSON from API how to access object?

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);
});

getting a specific value from JSON array with multiple arrays inside in javascript

I'm asking here as I can see this website the most one can help in this
I have an output value in JASON format as the following:
{
"total": 16,
"members": [{
"id": 4,
"name": "Blade11",
"descriptors": {
"os": "Windows 2012 / WS2012 R2"
},
"FCPaths": [{
"wwn": "50060B0000C27208",
"hostSpeed": 0
}, {
"wwn": "50060B0000C2720A",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 11,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 11\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}, {
"id": 6,
"name": "Blade4",
"descriptors": {
"os": "VMware (ESXi)"
},
"FCPaths": [{
"wwn": "50060B0000C27216",
"hostSpeed": 0
}, {
"wwn": "50060B0000C27214",
"hostSpeed": 0
}],
"iSCSIPaths": [],
"persona": 8,
"links": [{
"href": "https://3par:8080/api/v1/hostpersonas?query=\"wsapiAssignedId EQ 8\"",
"rel": "personaInfo"
}],
"initiatorChapEnabled": false,
"targetChapEnabled": false
}
what I want is, to parse this output for retrieving an output parameter with the name object only in a list or array of string
for example Names = Blade11, Blade4,....
if you can see in the Json output we have all the names under "members", then each one is another array of values, I want to retrieve only names
thanks
If this JSON is string first you have to parse it
var json = JSON.parse('here is your JSON string');
Than you can access to it properties like you work with object
var names = json.members.map(function(member) {
return member.name;
});
Since you already have JSON format, you can use an array method on the member key of your JSON object to iterate through each array item.
var names = [];
object_name.members.forEach((arrItem) => {
names.push(arrItem.name);
}
or
namesArray = object_name.members.map((arrItem) => {
return arrItem.name;
}
You could use Array#map for iterating all elements of the array and return only the name property.
If you have a JSON string, you need to parse it in advance for getting an object, like
object = JSON.parse(jsonString);
var jsonString = '{"total":16,"members":[{"id":4,"name":"Blade11","descriptors":{"os":"Windows 2012 / WS2012 R2"},"FCPaths":[{"wwn":"50060B0000C27208","hostSpeed":0},{"wwn":"50060B0000C2720A","hostSpeed":0}],"iSCSIPaths":[],"persona":11,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 11\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false},{"id":6,"name":"Blade4","descriptors":{"os":"VMware (ESXi)"},"FCPaths":[{"wwn":"50060B0000C27216","hostSpeed":0},{"wwn":"50060B0000C27214","hostSpeed":0}],"iSCSIPaths":[],"persona":8,"links":[{"href":"https://3par:8080/api/v1/hostpersonas?query=\\"wsapiAssignedId EQ 8\\"","rel":"personaInfo"}],"initiatorChapEnabled":false,"targetChapEnabled":false}]}',
object = JSON.parse(jsonString),
array = object.members.map(function (a) { return a.name; });
console.log(array);

Formatting JSON for Angular data binding

when my ajax call completes an array of json is returned
for my angular data binding to work perfectly, i need to merge all values in to a single JSON file. I have tried $.extend(), it's giving following output
Need a solution for this
for example if my response looks like this:
[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];
the output i need is :
{ test':'test', 'test':'test', 'test':'test', 'test':'test' }
Edit:
The final value will be associated to the ng-model automatically.
desired output example:
{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8
}
From what I understand you are trying to convert array of Json data into one singel json data. So you have array of values but you would want all of them in one variable. Try this
var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];
var finalData ="";
$.each(testData,function(index,value){
finalData += value +',';
});
finalData = finalData.replace(/\},\{/g,',').slice(0, -1);
document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Map just applies the function to every element in the array.
var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)
If you use underscore.js then can easily
like:
var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
var newList = _.extend.apply(null,[{}].concat(list));
then output will be
{ test1: "test1", test2: "test2", test3: "test3" }
Iterate over the array, convert every value to a JSON object, concatenate and then convert to a string back.
If you need fo this more times, you probably should make this a function.

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"]);

Categories

Resources