IBM Worklight - Parse JSON response - javascript

How I can parse JSON response inside my javascript code? After I invoke my worklight adapter, I got this result.
{"linkAccountList": [{
"accountRule": "1",
"accountCurrencyISO": "IDR",
"nickName": "",
"accountCurrency": "016",
"accountTypeDisplay": "",
"accountType": "",
"accountNo": "1001328000",
"accountHolderName": "LELY HERNAWATI"
}, {
"accountRule": "1",
"accountCurrencyISO": "IDR",
"nickName": "",
"accountCurrency": "016",
"accountTypeDisplay": "",
"accountType": "",
"accountNo": "30000000100677",
"accountHolderName": "LELY HERNAWATI"
}, {
"accountRule": "1",
"accountCurrencyISO": "IDR",
"nickName": "",
"accountCurrency": "016",
"accountTypeDisplay": "",
"accountType": "",
"accountNo": "2003500382",
"accountHolderName": "LELY HERNAWATI"
}]
}
Then I store the value inside sessionStorage.
sessionStorage.setItem("linkAccountList", result.invocationResult.linkAccountList);
After that I alert the value, it's not what I wanted even already JSON.stringify() it.
linkAccountList :: "[object Object],[object Object],[object Object]"
What I want is exactly like result above.
My success function
function welcomeSuccess(result){
WL.Logger.debug("List retrieve success");
busyIndicator.hide();
sessionStorage.setItem("linkAccountList", result.invocationResult.linkAccountList);
WL.Logger.debug("linkAccountList :: " + JSON.stringify(sessionStorage.linkAccountList));
}

SessionStorage will only store strings. When you put something into SessionStorage, you should stringify it and when getting it back, do a JSON.parse().
function welcomeSuccess(result){
WL.Logger.debug("List retrieve success");
busyIndicator.hide();
sessionStorage.setItem("linkAccountList", JSON.stringify(result.invocationResult.linkAccountList));
WL.Logger.debug("linkAccountList :: ", JSON.parse(sessionStorage.linkAccountList));
}
What happened in your case was that when it put the value in the SessionStorage, it invoked the toString() method of the array which returned "[object Object],[object Object],[object Object]" and that is what you got back.

Related

Script that stores multiple values from JSON dictionary into array

I have over 1000s of dictionaries in JSON after an API request. How do create a script that iterates over all dictionaries and stores the values of one of the key-value pairs?
example
},"testData"
{
"testJSON": "test",
"phone": null,
"address: "122 main st"
}, "testData1"
{
"testJSON": "test1",
"phone": null,
"address: "123 main st"
},
For example, how do I get the "address" field of every single JSON dictionary?
You need to first parse your json, like this:
var json = JSON.parse(jsonString);
then you could iterate your json keys and do something with the root values, like such:
for(var el in json)
{
console.log(json[el]) // will log every root element
console.log(json[el].phone) // will log phone of each element
}
example fiddle: https://jsfiddle.net/1ky6dzen/
In python this can be done like this:
data = [{
"testJSON": "test",
"phone": null,
"address: "122 main st"
}, "testData1"
{
"testJSON": "test1",
"phone": null,
"address: "123 main st"
}]
my_array = []
for obj in data:
my_array.append(obj['address'])
print(my_array)
Hope this is what you were after :)
Use forEach loop to iterate over the keys of the object
var a={"testData":
{
"testJSON": "test",
"phone": null,
"address": "122 main st"
}, "testData1":
{
"testJSON": "test1",
"phone": null,
"address": "123 main st"
}};
Object.keys(a).forEach(e=>console.log(a[e].address))

How to read Json data using ng-repeat

I am working with Express 3 version of the NodeJs and have a SQL query which fetched the data from the database and then I applied JSON.Stringify and then JSON.PARSE function on the results obtained from the SQL query.
My JSON data looks like something like this. result is something on which I am saving my results.
Output at Console of Node Eclipse:
Database Results: [object Object],[object Object],[object Object]
result [object Object],[object Object],[object Object]
On the Angular side I used the below methods:
$scope.myResult = response.jsonParse;
console.log($scope.myResult);
I am using the Firebug to see my results and I can see the data on Firebug console as in JSON format:
{
"jsonParse": [{
"ITEM_CODE": 3,
"ITEM_NAME": "SONY",
"ITEM_DESC": " 44 inches",
"ITEM_PRICE": 170,
"ITEM_QTY": 4,
"SELLER_FIRSTNAME": "sagar",
"SELLER_LASTNAME": "kaw",
"EMAIL": "sagar.kaw#gmail.com",
"SELLER_USERNAME": "sagkaw",
"category": "TV",
"Group_Name": "Electronics"
}, {
"ITEM_CODE": 4,
"ITEM_NAME": "GIBSON",
"ITEM_DESC": "ACOUSTIC ",
"ITEM_PRICE": 110,
"ITEM_QTY": 6,
"SELLER_FIRSTNAME": "sagar",
"SELLER_LASTNAME": "kaw",
"EMAIL": "sagar.kaw#gmail.com",
"SELLER_USERNAME": "sagkaw",
"category": "ENTERTAINMENT",
"Group_Name": "INSTRUMENTS"
}, {
"ITEM_CODE": 5,
"ITEM_NAME": "Marvel Avenger",
"ITEM_DESC": "Captain America ",
"ITEM_PRICE": 110,
"ITEM_QTY": 6,
"SELLER_FIRSTNAME": "sagar",
"SELLER_LASTNAME": "kaw",
"EMAIL": "sagar.kaw#gmail.com",
"SELLER_USERNAME": "sagkaw",
"category": "Kids Toy",
"Group_Name": "TOYS"
}]
}
I copied the JSON data to myResults:
}).success(function(response){
$scope.myResult = response.jsonParse;
Now I have to get this data print on my HTML where I am using
ng-repeat="result in myResult">
<p><Strong>Item Name : </Strong>{{result.ITEM_NAME}}</p>
<p><Strong>Item Description : </Strong>{{result.ITEM_DESC}}</p>
But its not printing anything.
But if I do
{{result}} : It prints whole data on the screen.
I have to print the data in differently for different Item code.
This happens because your myResult variable is binded to the whole data returned from your server. Instead of doing this
$scope.myResult = response.jsonParse;
do
$scope.myResult = response.data.jsonParse;

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;

Get data from JSON

I am trying to use Adapter for Push Notification. I followed all steps define in this IBM Worklight Developer site for Push Notification and make a project and its working. Now further i want to send notifications to a specific device. For this worklight give a method getDeviceSubscriptions() which return JSON array containing number of object for each subscribed device.
deviceSubscriptions = userSubscription.getDeviceSubscriptions() ;
the JSON include:
[{
"platform": "",
"eventSourceId": "",
"alias": "",
"token": "",
"userAgent": "",
"device": "",
"applicationId": "",
"options": {}
},
{
"platform": "",
"eventSourceId": "",
"alias": "",
"token": "",
"userAgent": "",
"device": "",
"applicationId": "",
"options": {}
}]
Now i want to get value of key device and token. So how can it can be achieved.
At that time i am using JSON.stringify it return a string but i want to have direct access to device and token. When i used JSON.parse it gives [object , Object] but not display any JSON.
After the JSON parse, use this to point out the key directly
obj[0]["device"]
For all the available node you should use incremental value in place of [0], like
obj[i]["device"];
i++;
Just access the properties using array syntax:
var firstDevice=deviceSubscriptions[0].device;
var secondDevice=deviceSubscriptions[1].device;
etc...
Update
Currently your JSON is not valid, the valid json should be :
{
"items": [
{
"platform": "Google",
"eventSourceId": "PushAdapter.PushEventSource",
"alias": "myPush",
"token": " ",
"userAgent": " ",
"device": " ",
"applicationId": " ",
"options": {}
},
{
"platform": "Google",
"eventSourceId": "PushAdapter.PushEventSource",
"alias": "myPush",
"token": " ",
"userAgent": " ",
"device": " ",
"applicationId": " ",
"options": {}
}
]
}
Parse your json string like :
var data = JSON.parse(yourJsonString);
Now access the device and token properties value like:
var device = data.items[0].device; //give device value of 0th item
var token = data.items[0].token; //give token value of 0th item
Check this fiddle

Iterate over JSON array

I've read several examples of how to do what I want but none seem to work. I want to iterate over a JSON array but it's not working for me. When I look in chromes js console my data looks like this:
"[\r\n {\r\n \"EntryId\": 3,\r\n \"Title\": \"Tiny Living For sales\",\r\n \"Description\": \"This is a house for sale\",\r\n \"AddressViewModel\": {\r\n \"AddressId\": 3,\r\n \"Street1\": null,\r\n \"Street2\": null,\r\n \"City\": \"Los Angeles\",\r\n \"LocationId\": 5,\r\n \"LocationName\": \"California\",\r\n \"PostalCode\": null,\r\n \"Phone\": null,\r\n \"Latitude\": 34.052234,\r\n \"Longitude\": -118.243685\r\n },\r\n \"EntryCategoryName\": \"Houses for Sale\",\r\n \"EventStartDate\": null,\r\n \"EventEndDate\": null\r\n },\r\n {\r\n \"EntryId\": 2,\r\n \"Title\": \"Tiny Living Workshop\",\r\n \"Description\": \"This is a workshop\",\r\n ...
And if I turn it into an object by doing so:
var myObject = eval('(' + locations + ')');
It looks like this (formated):
[
{
"EntryId": 3,
"Title": "Tiny Living For sales",
"Description": "This is a house for sale",
"AddressViewModel": {
"AddressId": 3,
"Street1": null,
"Street2": null,
"City": "Los Angeles",
"LocationId": 5,
"LocationName": "California",
"PostalCode": null,
"Phone": null,
"Latitude": 34.052234,
"Longitude": -118.243685
},
"EntryCategoryName": "Houses for Sale",
"EventStartDate": null,
"EventEndDate": null
},
{
"EntryId": 2,
"Title": "Tiny Living Workshop",
...
But when I try to iterate over it (either the raw JSON or the object) it gives me each letter of the JSON, not each object in the array
for (var i = 0; i < myObject.length; i++) { console.log(myObject[i]); }
Like so:
"
[
\
r
\
Thanks
You evaluate the JSON and assign the result to "myObject", and then you attempt to iterate through "locations". It's no wonder that that doesn't work :-)
I figured it out. I was returning the JSON from my controller like this
return Json( jsonResults, "text/html");
I had to do this on a different controller to prevent IE from prompting the user to save the JSON results.
Anyways, that was putting quotes around the data so it wasn't being parsed correctly.
So I am now returning:
return Json( jsonResults);
Hopefully I don't have the IE problem (tested in 9 and didn't see it)

Categories

Resources