Accessing Child in JSON Object - javascript

I have a JSON
{
"destination_addresses" : [ "14 Mission St, San Francisco, CA 94105, USA" ],
"origin_addresses" : [ "23 Mission St, San Francisco, CA 94103, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1.3 mi",
"value" : 2060
},
"duration" : {
"text" : "7 mins",
"value" : 444
},
"duration_in_traffic" : {
"text" : "6 mins",
"value" : 344
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I have been attempting to access the "text" value of duration_in_traffic and to store that value into a variable. For some reason I am getting the value to be undefined.
var hold = JSON.parse(body.rows.elements.duration.text);
Why cannot I access the child like this?

You have nested arrays, so you need to access the elements in the arrays by their index.
var hold = body.rows[0].elements[0].duration_in_traffic.text;

you need to parse the JSON string (if it is a string) first, then you can access it ... assuming body is the var that holds the string, you would do
var hold = JSON.parse(body).rows[0].elements[0].duration.text;
or
var obj = JSON.parse(body);
var hold = obj.rows[0].elements[0].duration.text;

JSON.parse does not parse part of a json string. if your json string is store in body for example, you need to parse it first:
var jsonObj = JSON.parse(body);
This will give you a javascript object to work with, then you can access the properties of the object as you have tried to do.
var hold = body.rows[0].elements[0].distance.text; //similar to #js91
Hope that helps!

Related

array in array filter - javascript

hello i need help with array , as you can see my data
{
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
I can access elements such as id , title or logo because they are not arrays.
How can I loop through the data inside the array since there is an array in the category in yield?
var data = this.database.filter((item) => item.type == searchType)
var data = this.database.filter((item) => item.category == searchCategory)
It's okay because my type value doesn't have an array.
But when I enter my category value, it only gets the first index[0]. It does not look at other indexes.
in summary,
item.category[0] , item.category[1] , item.category[2]...........
How can I get index browsing like
if your data looks like this :
let data ={
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
and if we have array of data you can do something like this :
myArray.filter(item=>item.category.indexOf(searchCategory)>=0)
but if you want to explore in object rather than array you can do this :
data.category.indexOf(searchCategory)>=0
You could make this a bit generic, by testing whether the targeted field is an array, using Array.isArray, and then call a filter on each element, and see if any is positive (using .some()). The filter can be function that is provided, so that it can perform a simple match, or apply a regular expression, or anything else.
Instead of testing with Array.isArray you could skip that step and check whether the value has a .some() method. If so, calling it will give the desired outcome, and otherwise (using the .? and ?? operators), the filter should be applied to the value as a whole:
Here is how that looks:
function applyFilter(data, field, filter) {
return data.filter(item => item[field]?.some(filter) ?? filter(item));
}
// Example use:
var data = [{
"category" : [ "Action", "Thriller", "Horror"],
"type" : "Series",
}, {
"category" : [ "Historical", "Romance" ],
"type" : "Theatre",
}];
// Find entries that have a category that looks like "roman*":
var result = applyFilter(data, "category", value => /^roman.*/i.test(value));
console.log(result);
If you are running on an older version of JavaScript, and don't have support for .? or ??, then use:
return data.filter(item => Array.isArray(item[field])
? item[field].some(filter)
: filter(item));

Accessing data from Object Javascript

I have created this object :
var hemicycle = {
Groupe : "Group1" [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};
I try to display some data from it but I can't access any.
When I type hemicycle in the dev tools of Chrome I get this :
I also tried to display "Group1" from the object but it won't let me, I typed this :
I don't know why my object is not defined ?
Any help is appreciated.
Well, the issue is, that you actually don't have a valid object. Groupe has really weird structure, what is it supposed to be? Array? Then try this:
var hemicycle = {
Groupe: [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};
Your problem is that your object itself is invalid.
Two ways to improve that. Choose whatever fits your needs best.
var hemicycle = {
Groupe : "Group1",
Content : [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};
var hemicycle = {
Groupe : [{
Member : [{
Name : "MemberName",
Siege : "SiegeNumber",
Vignette : "PhotoURL"
}]
}]
};
this simple example should solve your problem
var myObj = {
"1": { address: "44 buxton gardens berea durban", lat: "25.686", lng: "58.1156"},
"2": { address: "44 buxton gardens berea durban", lat: "0.0086", lng: "-0.00056"}
}
alert(myObj['1']['address']); //this get the address value of the first element
//using foreach statement to access the element and key
for (key in myObj){
alert(key); //this will display the 1
//use can say
alert(myObj[key]['address']); // this gets the value of address
}

extracting particular values from JSON

I am using Google Distance Matrix API and the response I got was in JSON:
{
"destination_addresses" : [ "Chandigarh, India" ],
"origin_addresses" : [ "Delhi, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "244 km",
"value" : 243506
},
"duration" : {
"text" : "3 hours 54 mins",
"value" : 14069
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I want to get the following values from JSON, destination_address, origin_address, distance, duration, and status. This is my code that I am trying out:
import requests as r
import json
a = r.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Delhi&destinations=Chandigarh&key=key")
#text form of a
tfa = a.text
print(tfa)
with open('data.json','w') as outfile:
json.dump(tfa,outfile)
json_data = json.loads(tfa)
print(json_data["destination_addresses"])
print(json_data["origin_addresses"])
print(json_data["rows"][0]["elements"][0]["distance"])
print(json_data["rows"]["elements"]["duration"])
The output that I am receiving gives me destination origin and distance, but I get an error when I try to grab duration, also the values inside the distance are printed as 'text':'244km','value':23432, but I only want to get the values not their labels. Is there any way to do that? Also is it possible to limit the values extracted inside the distance element (because I only want the text not the value)?
print(json_data["rows"][0]["elements"][0]["distance"]["value"])
Adding ["value"] to your current code will only show the value.
print(json_data["rows"]["elements"]["duration"])
You try to get something from the same level as the distance but you forget the [0] in this line. You can basically copy and paste the code that prints the distance value but replace distance by duration:
print(json_data["rows"][0]["elements"][0]["duration"]["value"])

How to access a part of a JSON file

Im trying to access some data and keep getting errors no matter what I try. Please help.
"rain":{"3h":13.625} is the part of the JSON file I am trying to access.
Here is what I have tried:
var currentRain = data.rain.3h; Which is most logical as it worked before but the number is what is giving the error.
var currentRain = data.rain["3h"];
var currentRain = data.rain[0]["3h"];
var currentRain = data.rain["3h"][0];
UPDATE:
This is the JSON payload:
{ "base" : "stations",
"clouds" : { "all" : 92 },
"cod" : 200,
"coord" : { "lat" : -33.850000000000001,
"lon" : 151.22
},
"dt" : 1429558616,
"id" : 6619279,
"main" : { "grnd_level" : 1024.97,
"humidity" : 100,
"pressure" : 1024.97,
"sea_level" : 1031.0999999999999,
"temp" : 288.77699999999999,
"temp_max" : 288.77699999999999,
"temp_min" : 288.77699999999999
},
"name" : "City of Sydney",
"rain" : { "3h" : 13.625 },
"sys" : { "country" : "AU",
"message" : 0.0101,
"sunrise" : 1429474880,
"sunset" : 1429514809
},
"weather" : [ { "description" : "heavy intensity rain",
"icon" : "10n",
"id" : 502,
"main" : "Rain"
} ],
"wind" : { "deg" : 157.5,
"speed" : 8.3200000000000003
}
}
You'll need to use ["bracket notation"] to access this, since "3h" begins with a number. As MDN explains:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
This is the correct JSON:
{
"rain": {
"3h": 13.625
}
}
First you need to parse it and transform into an object:
var jsonToObject = JSON.parse('{"rain":{"3h":13.625}}');
You can now access it like this:
jsonToObject.rain["3h"]
Just use data["rain"]. If you need to parse it first do JSON.parse(data) and then data["rain"].
OUTPUT
console.log(data["rain"]);
> { '3h': 13.625 }
...keep in mind that will return an Object.

merging javascript arrays for json

I serially collect information from forms into arrays like so:
list = {"name" : "John", "email" : "name#domain.com", "country" : "Canada", "color" : "blue"};
identifier = "first_round";
list = {"name" : "Harry", "email" : "othername#domain.com", "country" : "Germany"};
identifier = "second_round";
I want to combine them into something (I may have braces where I need brackets) like:
list_all = {
"first_round" :
{"name" : "John", "email" : "name#domain.com", "country" : "Canada", "color" : "blue"} ,
"second_round" :
{"name" : "Harry", "email" : "othername#domain.com", "country" : "Germany"}
};
so I can access them like:
alert(list_all.first_round.name) -> John
(Note: the name-values ("name", "email", "color") in the two list-arrays are not quite the same, the number of items in each list-array is limited but not known in advance; I need to serially add only one array to the previous structure each round and there may be any number of rounds, i.e. "third-round" : {...}, "fourth-round" : {...} and so on.)
Ultimately, I'd like it to be well-parsed for JSON.
I use the jquery library, if that helps.
Create list_all as a new object as follows:
var list_all = {};
list_all[identifier_1] = list_1;
list_all[identifier_2] = list_2;
// ...
JSON uses object literal notation. The form:
var person = {
"name": "Douglas Adams"
"age": 42
};
Is exactly the same (for all intents and purposes) as:
var person = new Object();
person.name = "Douglas Adams";
person.age = 42;
Does that help you?
You can also use
person["age"]
this is the same as
person.age
and to iterate through named properties:
//prints the person.propertyName for all propertyName in person
for (var propertyName in person) {
alert(person[propertyName]);
}
You can transmit data as a string, using it to interact with the server and converting it into an object, using jQuery. Ex:
var jsonString = "{'name': 'Douglas Adams', 'age': 42}";
jQuery.parseJson(jsonString); //returns this as an object
Search for JSON in the jQuery API docs: http://api.jquery.com/

Categories

Resources