jQuery Pull array from JSON response into new variable - javascript

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)

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.

Indexing array values in an object in an IndexedDB

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 :(

How do I access values in a d3 json file with nested array objects

Previously I was using a json file with the following format:
[{"lat":43.788458853157117,"lng":-79.282781549043008,"category":"volunteer","name":"Rita","url":"", "description":"xxx is a member of 13"},{"lat":43.7,"lng":-79.4,"category":"organization","name":"TCAN","url":"http://tcan.ca","description":"Lorem ipsum"}]
Now I am attempting to generate the json file from a Drupal site and am getting the following structure. How can I reference the lowest level fields. I have looked at examples using d3.net but have not found any that apply.
{
"organizations": [
{
"member": {
"field_category": "organization",
"body": "A network of organizations in Toronto devoted to climate change mitigation and adaptation.",
"URL": "xxx.ca",
"title": "Toronto Climate Action Network",
"field_lat": 43.7,
"field_long": -79.4
}
},
{
"member": {
"field_category": "abc",
"body": "xxx.",
"URL": "",
"title": "yyy",
"field_lat": 43.7,
"field_long": -79.28
}
}
]
}
Assuming that your data is stored in the variable data:
var bottom = data.organizations.map(function(d) { return d.member; });

JSON parsing in JS

I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on

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