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)
Related
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))
I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?
A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status
Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);
User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});
Thank you for the help in advance. I am using a plugin which is expecting a JSON response to be an array not a object. Below is a sample of the JSON response I am getting
{
"instruments": [
{
"id": 3316,
"code": "WES",
"market_code": "ASX",
"name": "Wesfarmers Limited",
"currency_code": "AUD",
"pe_ratio": 16.38,
"nta": 4.44,
"eps": 2.55,
"current_price": 41.78,
"current_price_updated_at": "2017-10-26T16:10:09.000+11:00",
"sector_classification_name": "Retail Trade",
"industry_classification_name": "Food Retail",
"security_type": "Ordinary Shares",
"registry_name": "Computershare"
},
{
"id": 2955,
"code": "RIO",
"market_code": "ASX",
"name": "Rio Tinto Limited",
"currency_code": "AUD",
"pe_ratio": 14.95,
"nta": 27.77,
"eps": 4.66,
"current_price": 69.66,
"current_price_updated_at": "2017-10-26T16:10:11.000+11:00",
"sector_classification_name": "Non-Energy Minerals",
"industry_classification_name": "Other Metals/Minerals",
"security_type": "Ordinary Shares",
"registry_name": "Computershare"
},
],
"links": {}
}
The array I need to pull out into its own JSON object is the instruments array.
Now typically I know I would access that data via (if the response variable was called data) data.instruments[0].name as a example which would give me Wesfarmers limited
but if I want that entire array to sit in a new variable, which can then be parsed, how can I get that to happen?
Cheers
arr=new Array(data.instruments)
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;
For a Chrome app, wich stores data in IndexedDB, i have a object like this:
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"parcels": [
{
"service": "DHL",
"track": "12345"
},
{
"service": "UPS",
"track": "3254231514"
}
]
}
If i store the hole object in an objectStore, can i use an index for "track", which can be contained multiple times in each order object?
Or is it needed or possibly better/faster to split each object into multiple objectStores like know from relational DBs:
order
orderitem
parcel
The solution should also work in a fast way with 100.000 or more objects stored.
Answering my own question: I have made some tests now. It looks like it is not possible to do this with that object in only 1 objectStore.
An other example object which would work:
var myObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"shipping": {"method": "letter",
"company": "Deutsche Post AG" }
}
Creating an index will be done by:
objectStore.createIndex(objectIndexName, objectKeypath, optionalObjectParameters);
With setting objectKeypath it is possible to address a value in the main object like "name":
objectStore.createIndex("name", "name", {unique: false});
It would also be possible to address a value form a subobject of an object like "shipping.method":
objectStore.createIndex("shipping", "shipping.method", {unique: false});
BUT it is not possible to address values like the ones of "track", which are contained in objects, stored in an array. Even something like "parcels[0].track" to get the first value as index does not work.
Anyhow, it would be possible to index all simple elements of an array (but not objects).
So the following more simple structure would allow to create an index entry for each parcelnumber in the array "trackingNumbers":
var simplifiedOrderObject = {
"ordernumber": "123-12345-234",
"name": "Mr. Sample",
"address": "Foostreet 12, 12345 Bar York",
"orderitems": [
{
"item": "brush",
"price": "2.00"
},
{
"item": "phone",
"price": "30.90"
}
],
"trackingNumbers": ["12345", "3254231514"]
}
when creating the index with multiEntry set to true:
objectStore.createIndex("tracking", "trackingNumbers", {unique: false, multiEntry: true});
Anyhow, the missing of the possibility to index object values in arrays, makes using indexedDB really unneeded complicated. It's a failure in design. This forces the developer to do things like in relational DBs, while lacking all the possibilities of SQL. Really bad :(