How to extract specific info from json - javascript

I am trying to get the subdivisions.names.en from the json below but keep getting a "TypeError: location.subdivisions.names is undefined" error. I'm sure it something simple & prob just need more sleep ;)
I can get other the info I need - this works:
alert(location.city.names.en + ' ' + location.postal.code);
But this does not:
alert(location.subdivisions.names.en);
Here is my json:
{
"continent": {
"code": "OC",
"geoname_id": xxx,
"names": {
"fr": "Océanie",
"pt-BR": "Oceania",
"zh-CN": "大洋洲",
"es": "Oceanía",
"de": "Ozeanien",
"ja": "オセアニア",
"en": "Oceania",
"ru": "Океания"
}
},
"location": {
"longitude": xxxx,
"latitude": -xxxx,
"time_zone": "Australia/Melbourne"
},
"subdivisions":
[
{
"names": {
"ru": "Виктория",
"pt-BR": "Vitória",
"en": "Victoria"
},
"iso_code": "VIC",
"geoname_id": xxxx
}
],
}

"subdivisions": [ ... indicates, that this variable is an array of objects. You need to index the proper entry:
alert(location.subdivisions[0].names.en);
Please be aware that there must not be any entry
"subdivisions": [], ...
and a lot of them, so there must be some logic / check on the index.
location.subdivisions.length might help

"subdivisions" is defined as an array in your json file. Depending on what is intended, either change it to be just a hash (remove the square brackets) or modify the access to
alert(location.subdivisions[0].names.en);

You should have a look at what is JSON and how to use it properly because apparently you seem to lack the basic knowledge of how JSON is structured.
That being said, the reason why location.subdivisions.names.en is undefined is because in your JSON it does not exist.
subdivisions is also an array of objects.
In order to access what you are trying to you must use subdivisions[0].names.en.

Related

Can't access variables of JSON response from REST-API in Javascript

I have a problem getting access to the variables in a JSON-File. I get the file as a response from a REST-API. Here you can see the JSON-File:
{
"_embedded": {
"events": [
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
I want to access the value (Josh) of the "name" variable in Javascript in line number 5 and store it into a new variable to use it later.
This ist how I try to do it:
var = data._embedded.events[0].name
But I can't get access to the value attached to "name".
I have read the answers to similar questions here, but there was no solution for me.
I have only read, that it does not work because of the wrong JSON-structure. In other threads, they say there has to be a "{" instead of a "[" in line 3. But I don't know how to change it in javascript directly. I tried it with the JSON.stringify()-method but it didn't work out.
Can somebody help me, please? Is there any way to get access?
I hope you can understand my problem.
Thank you very much!
It seems that your json structure has some errors. The json structure similar to the following is legal. Of course, it is no problem to use a legal structure to exec data._embedded.events[0].name.
const data = {
"_embedded": {
"events": [
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
},
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
},
//...
]
}
}
console.log(data._embedded.events[0].name)

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

Define JSON-LD #context to join/split values?

I'd like to use the expand and compact methods of the jsonld.js library to translate data from various sources into a common format for processing. If I take a source JSON document, add a #context to it, then pass it through the expand method I'm able to get the common format that I need.
The use case that I haven't been able to find a solution for is when multiple values need to be merged. For example, schema.org defines a PostalAddress with a single field for the streetAddress, but many systems store the street address as separate values (street number, street name, street direction...). To translate the incoming data to the schema.org format I need a way to indicate in my #context that multiple fields make up the streetAddress, in the correct order.
Compacted Document
{
"#context": {
"displaName": "http://schema.org/name",
"website": "http://schema.org/homepage",
"icon": "http://schema.org/image",
"streetNumber": "http://schema.org/streetAddress"
},
"displaName": "John Doe",
"website": "http://example.com/",
"icon": "http://example.com/images/test.png",
"streetNumber": "123",
"streetName": "Main St",
"streetDirection": "South"
}
Expanded Document
{
"http://schema.org/name":[
{
"#value":"John Doe"
}
],
"http://schema.org/image":[
{
"#value":"http://example.com/images/test.png"
}
],
"http://schema.org/streetAddress":[
{
"#value":"123"
}
],
"http://schema.org/homepage":[
{
"#value":"http://example.com/"
}
]
}
I've reviewed all of the JSON-LD specs that I could find and haven't been able to locate anything that indicates a way to split or concatenate values using the #context.
Is anyone aware of a way to map multiple values into one context property, in the correct order, and possibly add whitespace between the values. I also need to find a solution for the reverse scenario, where I need to split one field into multiple values, in the correct order.
Note: Even if I map all three properties to streetAddress, the values will all be included in the array, but there's no guarantee they'll be in the correct order.
One possible way to achieve this is to use a single array field for your address containing the ordered address components (i.e. ["number", "direction", "name"]). Then in the #context you can specify the address with #container: #list, which will ensure the address components are correctly ordered.
So the compacted document would be:
{
"#context": {
"displaName": "http://schema.org/name",
"website": "http://schema.org/homepage",
"icon": "http://schema.org/image",
"address": {
"#id": "http://schema.org/streetAddress",
"#container": "#list"
}
},
"displaName": "John Doe",
"website": "http://example.com/",
"icon": "http://example.com/images/test.png",
"address": ["123", "South", "Main St"]
}
And the expanded one would be
{
"http://schema.org/streetAddress": [
{
"#list": [
{
"#value": "123"
},
{
"#value": "South"
},
{
"#value": "Main St"
}
]
}
],
"http://schema.org/name": [
{
"#value": "John Doe"
}
],
"http://schema.org/image": [
{
"#value": "http://example.com/images/test.png"
}
],
"http://schema.org/homepage": [
{
"#value": "http://example.com/"
}
]
}
I posted an issue on the jsonld.js Github repository. According to #dlongley, the original creator of the jsonld.js library, it's not possible to manipulate properties in this manor, using standard JSON-LD.
https://github.com/digitalbazaar/jsonld.js/issues/115

How do I create a subset of a JSON file using key values that exist in both using getJSON?

I have a large JSON file that I want to use to create a subset using vars that I'll be storing in localStorage. I prefer jQuery but other approaches are welcomed.
The id (which will exist in both places) will be used to match and determine that the keys/values should be part of the new subset.
The "master" JSON file is structured similar to this:
{
"myStuff": [
{
"id": "53b0c01de4b0deedb5c9015f",
"brief": "Joe's Stuff",
"author": "Joe"
},
{
"id": "545fb8c4e4b03cfb303de9f2",
"brief": "Jim's Stuff",
"author": "Jim"
},
{
"id": "54676ae4e4b09ffed41ffc7c",
"brief": "Mary's Stuff",
"author": "Mary"
}
]
}
I have flexibility in how the items that will determine the subset are presented.It will always contain multiple values. Those are "id" value to match an existing "id" value in the master JSON file.
For example, I can get a string out of localStorage that would look like this:
{"id1":"545fb8c4e4b03cfb303de9f2","id2":"54676ae4e4b09ffed41ffc7c"}
or as simple as this:
545fb8c4e4b03cfb303de9f2, 54676ae4e4b09ffed41ffc7c
Suggestions to which approach may be better are welcomed.
So, in this case, The subset should return just the stuff from Jim and Mary and ignore Joe.
{
"myStuffSubset": [
{
"id": "545fb8c4e4b03cfb303de9f2",
"brief": "Jim's Stuff",
"author": "Jim"
},
{
"id": "54676ae4e4b09ffed41ffc7c",
"brief": "Mary's Stuff",
"author": "Mary"
}
]
}
Please let me know if I've missed something in the explanation. And, I find fiddles help me learn the best. Thanks!
I've created a plnkr for you.
Basically, the filter function will get the string separated by commas and search inside your JSON:
function search(str, obj) {
var arr = str.split(',');
return obj.myStuff.filter(function(o) {
return arr.indexOf(o.id) > -1;
});
}

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

Categories

Resources