JavaScript access object - javascript

How can I get the "name" of the following JSON object?
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
}
["name"] returns the followin error
TypeError: Cannot read property 'name' of undefined

This could help you if not then let me know. If your json object is same as your_json_obj then you have to parse it first using JSON.parse(your_json_obj). If not then you simply use your_json_obj.location.name
const your_json_obj = "{
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
},
...}"
const name = JSON.parse(your_json_obj).location.name
console.log(name)

You can access its properties using location.name, location["name"], for example:
const location = {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 14:44",
"localtime_epoch": 1587566640,
"utc_offset": "2.0"
}
location.name;
location.["name"]
If you want to use it from the JSON object:
var y = '{"location": { "name": "Hilden", "country": "Germany", "region": "Nordrhein-Westfalen", "lat": "51.167", "lon": "6.933", "timezone_id": "Europe/Berlin", "localtime": "2020-04-22 15:03", "localtime_epoch": 1587567780, "utc_offset": "2.0" }}';
JSON.parse(y).location.name
So, in this case, you should use JSON.parse(jsonObject)) before access its properties. BUT NOTICE: "Make sure the text is written in JSON format, or else you will get a syntax error.", a "large text" inside {} - https://www.w3schools.com/js/js_json_parse.asp

Related

Verify String is displaying within Nested JSON using Postman

I am working on Postman to verify some API calls, upon which I have gone through one of the end point, whose response is give below, and I need to make sure that within that JSON response:
[
{
"contact": {
"id": "k72yk2iwrf",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "9208113975",
"eventId": "TESTLIBRA-10"
}
},
{
"contact": {
"id": "w4c4f2i7l4",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "6803424516",
"eventId": "TESTLIBRA-10"
}
}
]
I can make sure that "eventId" is displaying and it is displaying "TESTLIBRA-10" value.
No matter, how long JSON response is, It can verify that this property , along with that value of that property are displaying.
I got my answer by myself, what I did was:
var jsonArrayData = pm.response.json();
pm.test('EventID property is displaying throughout JSON', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration).to.have.property("eventId")
})
})
pm.test('Entered Libra EventID is entered', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration.eventId).to.eql("TESTLIBRA-10")
})
})

How to convert multi nested object into multidimensional array using javascript?

Current format:
{
"SD": {
"Key": "SD",
"City": "San Diego",
"Name": "Padres"
},
"WSH": {
"Key": "WSH",
"City": "Washington",
"Name": "Nationals"
}
}
Expected format:
[
{
"Key": "SD",
"City": "San Diego",
"Name": "Padres"
},
{
"Key": "WSH",
"City": "Washington",
"Name": "Nationals"
}
]
You can do that with Object.values(...) which makes an array out of all the values from your object:
const obj = {
"SD": {
"Key": "SD",
"City": "San Diego",
"Name": "Padres"
},
"WSH": {
"Key": "WSH",
"City": "Washington",
"Name": "Nationals"
}
}
console.log(Object.values(obj));
It looks like Object.values is the answer, you can use it like this.
Object.values(your_object)
And it will return your expected format, here is the documentation on how it works if you would like to read further.
Object.values Documentation

Extract and rename JSON object to different format

I'm requesting venue data from the Foursquare API but it is not returned in the geoJSON format. I haven't worked with JSON before and I do not have any idea how to approach doing this.
Will I loop through the object and build a JavaScript array of the necessary object values ? How do I select all of the values with the same key ? Is it possible just to delete particular values out of the JSON response and rename the others as desired ? What is the best approach here ?
Below I have posted both the input and the desired output of what I would like to achieve.
INPUT
{
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
}
OUTPUT
[{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.99389265510277, 40.703032453630854]
},
"properties": {
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.703032453630854,
"lng": -73.99389265510277
}
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-73.9979327420479, 40.69957016220184]
},
"properties": {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220184,
"lng": -73.9979327420479
}
}
}]
You can do this by saving the response into variable. Don't forget to JSON.parse it. Then you can do the following to convert it into your own format by using Array#map method.
let obj = {
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
};
let res = obj.response.venues.map((venue) => {
let o = {};
o.type = "feature";
o.geometry = {
type: "Point",
coordinates: [venue.location.lng, venue.location.lat]
};
o.properties = venue;
return o;
});
console.log(res);
You can save the result from your request to the Foursquare API as a variable and then loop through it to get the information you need:
var result = {
"meta": {
"code": 200,
"requestId": "57c63303498e78d449981c2c"
},
"response": {
"venues": [{
"id": "430d0a00f964a5203e271fe3",
"name": "Brooklyn Bridge Park",
"location": {
"address": "Main St",
"crossStreet": "Plymouth St",
"lat": 40.70303245363086,
"lng": -73.99389265510275
}
}, {
"id": "51eabef6498e10cf3aea7942",
"name": "Brooklyn Bridge Park - Pier 2",
"contact": {},
"location": {
"address": "Furman St",
"crossStreet": "Brooklyn Bridge Park Greenway",
"lat": 40.69957016220183,
"lng": -73.99793274204788
}
}]
}
}
for(i=0;i<result.response.venues.length;i++) {
console.log(result.response.venues[i].name)
}
Console Result:
Brooklyn Bridge Park
Brooklyn Bridge Park - Pier 2
Instead of logging this to the console, you could then write the data into a new JS object the way you described in your output. Question is, do you really need to? The information is right there... rewriting it to a new object should not be necessary.

parse json based on dynamic value

I have a json that I'd like to parse based on the 'zone' field in order to get a list of region etc through a select input.
var data = {
"zone01": [{
"region": "North",
"state": "New York",
"county": "Albany",
"code": "01"
}, {
"region": "North",
"state": "New York",
"county": "Albany",
"code": "05"
}, {
"region": "North",
"state": "Maine",
"county": "Auburn",
"code": "07"
}],
"zone02": [{
"region": "South",
"state": "Florida",
"county": "Gainseville",
"code": "82"
}, {
"region": "South",
"state": "Florida",
"county": "Macclenny",
"code": "73"
}]
};
I can parse it by using:
function setValues(range, zone, region, state, country){
if(range === 'zone'){
var getRegions = _.groupBy(data.zone02, 'region');
$.each(getRegions, function(k, v){
var region = JSON.stringify(k);
region = region.replace(/"/g,'');
$('select#region').append('<option value="'+region+'">'+region+'</option>');
});
}
}
But what I really need is _.groupBy(data.zone02, 'region') with data.zone02 being data + the function's variable zone
UPDATE
Here's my finished product, sans readability and re-usability: jsFiddle
Use bracket notation to reference a property using a variable.
data[zone]

Displaying Dictionary in Javascript Object

I'm returning this response from my server:
callback({"City": "Miami", "State": "FL", "Street": "9th Street", "Name": "Big 12", "Zip": "65201", "Lat": -48.219999999999999, "Telephone": "5732168906", "Long": 32.0, "Events": "[{\"End Time\": \"2011-01-22 23:36:31\", \"Name\": \"Margaritas\", \"Start Time\": \"2011-01-22 15:36:31\"}, {\"End Time\": \"2011-01-22 19:36:39\", \"Name\": \"Dollar Bottles\", \"Start Time\": \"2011-01-22 15:36:39\"}, {\"End Time\": \"2011-01-23 23:36:31\", \"Name\": \"All You Can Drink\", \"Start Time\": \"2011-01-23 15:36:31\"}]"})
Here is where I'm attempting to parse the response and display it within my "tonight-list". With data.Events, I get the entire array of dictionaries displayed on screen.
function callback(data){
console.log(data);
$("#tonight-list").append("<li role='option' tabindex='0' class='ui-li ui-li-static ui-btn-up-c'>Starts:" +
data.Events +
"<li>");
However, I cannot figure out how to access each element (Start Time, End Time, Name, etc.). When I try data.Events[0], it gives me just the first character from data.Events.
How do I access each dictionary key in the array of Events? I just cannot figure out the syntax - it would be nice if I could see all the options on this object type. Thanks for the help in advance!
Make the Events in the JSON response a real array instead of a string, then you can use it like this:
var obj = JSON.parse(reponseText);
var event = obj.Events[0];
alert(event["End Time"]); // hurray
JSON response
callback({
"City": "Miami",
"State": "FL",
"Street": "9th Street",
"Name": "Big 12",
"Zip": "65201",
"Lat": -48.219999999999999,
"Telephone": "5732168906",
"Long": 32.0,
"Events": [{
"End Time": "2011-01-22 23:36:31",
"Name": "Margaritas",
"Start Time": "2011-01-22 15:36:31"
},
{
"End Time": "2011-01-22 19:36:39",
"Name": "Dollar Bottles",
"Start Time": "2011-01-22 15:36:39"
},
{
"End Time": "2011-01-23 23:36:31",
"Name": "All You Can Drink",
"Start Time": "2011-01-23 15:36:31"
}]
})​;
JSON dude! just return valid JSON from your server and use evalJSON. Then you can access each object via their corresponding keys.
edit:
basically do,
data.responseText.evalJSON();

Categories

Resources