javascript object variable with # sign [duplicate] - javascript

This question already has answers here:
How can I access object properties containing special characters?
(2 answers)
Closed 8 years ago.
i'm trying to pull some data from last.fm.
i get the following reply:
{
"tracks": {
"track": [
{
"name": "Once Upon a Dream",
"duration": "203",
"loves": "738",
"mbid": "92078817-2e04-4bcd-9c43-ebb9c2d1823c",
"url": "http://www.last.fm/music/Lana+Del+Rey/_/Once+Upon+a+Dream",
"streamable": {
"#text": "0",
"fulltrack": "0"
},
"artist": {
"name": "Lana Del Rey",
"mbid": "b7539c32-53e7-4908-bda3-81449c367da6",
"url": "http://www.last.fm/music/Lana+Del+Rey"
},
"image": [
{
"#text": "http://userserve-ak.last.fm/serve/34s/96432461.png",
"size": "small"
},
{
"#text": "http://userserve-ak.last.fm/serve/64s/96432461.png",
"size": "medium"
},
{
"#text": "http://userserve-ak.last.fm/serve/126/96432461.png",
"size": "large"
},
{
"#text": "http://userserve-ak.last.fm/serve/300x300/96432461.png",
"size": "extralarge"
}
]
}
And so on...
The problem lies when trying to access the image portion of the reply, the image object seems to have #text as variable name of the info i'm trying to access. a normal response.tracks.track[i].image[0].text obviously doesn't work.
is there some special way to access this variable ?

You can use the square bracket notation to access that variable like so:
response.tracks.track[i].image[0]['#text']

It's just a key name inside of the object. You cannot access it via dot notation since it contains an invalid characters but you can use bracket notation. Here's a really simple example demonstrating this.
var foo = {
'#bar': 'http://www.google.com/'
}
foo['#bar'] // will return a string value of http://www.google.com/
If your key contains any invalid characters it must be encased in a string. In your case, you're getting a JSON response which always contain string-encased key names.
Hope this helps!

Related

Accessing value in nested object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I don't understand how I can access an value in a object that is an array with an object inside itself.
I've tried with the dot notation and [] and array.reduce. But I'm doing something wrong.
I've changed the values but the structure remains the same:
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
I need to get the values of time and type, but I get undefined.
The final object is first element of array so you need to first access its first element.
const obj = {
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
}
console.log(obj.test.info[0].time);
console.log(obj.test.info[0].type);
Use the dot notation to access the properties
Object a consists of the test object which in-turn contains the key info whose value is an array containing one object with the required keys
a->test->info->[{time,type}]
var a = {
"test": {
"title": "My title",
"category": null,
"info": [{
"time": 10,
"type": "minutes"
}]
}
}
console.log(a.test.info[0].time)
console.log(a.test.info[0].type)

How would I define duplicate keys in a json array? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I am making a program that parses json files for dnd information. I have completed the program, however, I cannot figure out how to define the duplicate keys for the various attacks without manually giving thousands of keys unique ids.
Part of my JSON file:
{
"special_abilities": [
{
"name": "Legendary Resistance (3/Day)",
"desc": "If the tarrasque fails a saving throw, it can choose to succeed instead.",
"attack_bonus": 0
},
{
"name": "Magic Resistance",
"desc": "The tarrasque has advantage on saving throws against spells and other magical effects.",
"attack_bonus": 0
},
{
"name": "Reflective Carapace",
"desc": "Any time the tarrasque is targeted by a magic missile spell, a line spell, or a spell that requires a ranged attack roll, roll a d6. On a 1 to 5, the tarrasque is unaffected. On a 6, the tarrasque is unaffected, and the effect is reflected back at the caster as though it originated from the tarrasque, turning the caster into the target.",
"attack_bonus": 0
},
{
"name": "Siege Monster",
"desc": "The tarrasque deals double damage to objects and structures.",
"attack_bonus": 0
}
]
}
So, how would I define each of the name keys?
If I can define what I posted up there as searchFile.special_abilities, how would I define searchFile.special_abilities.name?
Your JSON is valid. You would access the parsed JSON data like so:
const searchFile = JSON.parse(jsonVarName)
const index = 2 // or whatever index you want
const name = searchFile.special_abilities[index].name
You can also use the various array methods to do all sorts of interesting things with the data, like searching by name:
const siegeMonster = searchFile.special_abilities.find(ability => ability.name === 'Siege Monster')
I'd suggest using a object of arrays instead, indexed by name, that way the name is never duplicated, and there's no need for separate unique identifiers. For example:
"special_abilities": {
"Some Name": [
{
"desc": "Description 1",
"attack_bonus": 0
},
{
"desc": "Description 2",
"attack_bonus": 5
}
],
"Some Other Name": [
{
"desc": "Some Other Description",
"attack_bonus": 2
}
]
}
Then, you could access special_abilities['Some name'] to get to the array, and iterate over the array to find what you're looking for. (Use Object.entries to get both the key and the value at once, eg Object.entries(special_abilities).forEach(([name, arr]) => { ... )

unable to access JSON child elements

I was trying to iterate following JSON object. when i try to access the content-items using page.content-items getting error.Is it not possible to access an object which have a key with "-"?.Please give a solution how to access this object.
{
"page": {
"title": "Romantic Comedy",
"total-content-items" : "54",
"page-num-requested" : "1",
"page-size-requested" : "20",
"page-size-returned" : "20",
"content-items": {
"content": [
{
"name": "The Birds",
"poster-image": "poster1.jpg"
},
{
"name": "Rear Window",
"poster-image": "poster2.jpg"
},
{
"name": "Family Pot",
"poster-image": "poster3.jpg"
}
]
}
}
}
It is possible to access the key with the - character, but not using dot notation. You need to use brakcet notation:
page['content-items']
to access the property.
Just use string value like in arrays:
page['content-items']
Use page['content-items'] because content-item is not a valid JavaScript identifier.

Extract image value from an object [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 5 years ago.
I have an object like this :
var obj = [
{
"id": 728,
"title": "A long day",
"images": {
"illustration": {
"title": "Preview",
"16x9": {
"1248x702": "https://example.com/image/225944d77559.jpg",
"1920x1080": "https://example.com/image/4546b05422594.jpg"
}
}
}
}
];
I'm trying for some time to get the 1920x1080 value, but without success :
alert(obj[0].title); //works
alert(obj[0].images.illustration.title); // works
alert(obj[0].images.illustration.16x9.1920x1080); // doesn't work and break the code
alert(obj[0].images.illustration.'16x9'.'1920x1080'); // doesn't work and break the code
I need your help. What should I do to get the 1920x1080 entry correctly ?
Use bracket:
var obj = [
{
"id": 728,
"title": "A long day",
"images": {
"illustration": {
"title": "Preview",
"16x9": {
"1248x702": "https://example.com/image/225944d77559.jpg",
"1920x1080": "https://example.com/image/4546b05422594.jpg"
}
}
}
}
];
console.log(obj[0].images.illustration['16x9']['1920x1080']);
Try this,
alert(obj[0].images.illustration['16x9']['1920x1080']);
You should write next:
obj[0].images.illustration['16x9']['1920x1080']
In JS if you have object key with specific sympols you should wrap this in Square brackets ['1920x1080'], its like you get elemet from array.

How to extract specific info from json

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.

Categories

Resources