Want to get a specific Element from a json array, - javascript

I havethe following JSON array and want to fetch a specific element from it for example the first element "long_name"
this is my JSON array:
({results:[{address_components:[{long_name:"Lahore", short_name:"Lahore", types:["locality", "political"]}, {long_name:"Lahore District", short_name:"Lahore District", types:["administrative_area_level_2", "political"]}, {long_name:"Punjab", short_name:"Punjab", types:["administrative_area_level_1", "political"]}, {long_name:"Pakistan", short_name:"PK", types:["country", "political"]}], formatted_address:"Lahore, Pakistan", geometry:{bounds:{northeast:{lat:31.6332872, lng:74.505512}, southwest:{lat:31.3342113, lng:74.1469001}}, location:{lat:31.55460609999999, lng:74.3571581}, location_type:"APPROXIMATE", viewport:{northeast:{lat:31.6332872, lng:74.505512}, southwest:{lat:31.3342113, lng:74.1469001}}}, place_id:"ChIJ2QeB5YMEGTkRYiR-zGy-OsI", types:["locality", "political"]}], status:"OK"})
Please help me on this..Thanks1

var data = {results:[{address_components:[{long_name:"Lahore", short_name:"Lahore", types:["locality", "political"]}, {long_name:"Lahore District", short_name:"Lahore District", types:["administrative_area_level_2", "political"]}, {long_name:"Punjab", short_name:"Punjab", types:["administrative_area_level_1", "political"]}, {long_name:"Pakistan", short_name:"PK", types:["country", "political"]}], formatted_address:"Lahore, Pakistan", geometry:{bounds:{northeast:{lat:31.6332872, lng:74.505512}, southwest:{lat:31.3342113, lng:74.1469001}}, location:{lat:31.55460609999999, lng:74.3571581}, location_type:"APPROXIMATE", viewport:{northeast:{lat:31.6332872, lng:74.505512}, southwest:{lat:31.3342113, lng:74.1469001}}}, place_id:"ChIJ2QeB5YMEGTkRYiR-zGy-OsI", types:["locality", "political"]}], status:"OK"};
alert(data.results[0].address_components[0].long_name);

You need to parse the JSON results, like so
var results = '{"results":[{"address_components":[{"long_name":"Lahore", "short_name":"Lahore", "types":["locality", "political"]}, {"long_name":"Lahore District", "short_name":"Lahore District", "types":["administrative_area_level_2", "political"]}, {"long_name":"Punjab", "short_name":"Punjab", "types":["administrative_area_level_1", "political"]}, {"long_name":"Pakistan", "short_name":"PK", "types":["country", "political"]}], "formatted_address":"Lahore, Pakistan", "geometry":{"bounds":{"northeast":{"lat":31.6332872, "lng":74.505512}, "southwest":{"lat":31.3342113, "lng":74.1469001}}, "location":{"lat":31.55460609999999, "lng":74.3571581}, "location_type":"APPROXIMATE", "viewport":{"northeast":{"lat":31.6332872, "lng":74.505512}, "southwest":{"lat":31.3342113, "lng":74.1469001}}}, "place_id":"ChIJ2QeB5YMEGTkRYiR-zGy-OsI", "types":["locality", "political"]}], "status":"OK"}';
var json = JSON.parse(results);
alert(json.results[0].address_components[0].long_name); //will show 'Lahore'

A JSON object is a list of lists. In order to access lower layers you first need to parse the JSON object and create an array.
var jsonArray = JSON.parse(json_object);
Then you need to create an array from the array index that you need to reach.
var address_components = jsonArray[0];
Then you would need to go a step down again.
var long_name = address_components[0].long_name;

It is difficult to see the exact path with the JSON all on one line. Formatting it in a more "human viewable" format renders as follows:
({
results: [
{
address_components: [
{
long_name: "Lahore",
short_name: "Lahore",
types: [
"locality",
"political"
]
},
{
long_name: "Lahore District",
short_name: "Lahore District",
types: [
"administrative_area_level_2",
"political"
]
},
{
long_name: "Punjab",
short_name: "Punjab",
types: [
"administrative_area_level_1",
"political"
]
},
{
long_name: "Pakistan",
short_name: "PK",
types: [
"country",
"political"
]
}
],
formatted_address: "Lahore, Pakistan",
geometry: {
bounds: {
northeast: {
lat: 31.6332872,
lng: 74.505512
},
southwest: {
lat: 31.3342113,
lng: 74.1469001
}
},
location: {
lat: 31.55460609999999,
lng: 74.3571581
},
location_type: "APPROXIMATE",
viewport: {
northeast: {
lat: 31.6332872,
lng: 74.505512
},
southwest: {
lat: 31.3342113,
lng: 74.1469001
}
}
},
place_id: "ChIJ2QeB5YMEGTkRYiR-zGy-OsI",
types: [
"locality",
"political"
]
}
],
status: "OK"
})
This way you can see that the json object contains a property of results which is an array. The elements of results contain an address_components property which is also an array. The elements of address_components contain the long_name property. To access this, you would do the following, assuming you have a JSON string stored in jsonString:
var jsonObject = JSON.parse(jsonString);
var firstLongNameProperty = jsonObject.results[0].address_components[0].long_name;

First off you should construct a valid JSON string so you need to put quotes around your keys like so...
'{"results": [{"address_components": [{"long_name": "Lahore","short_name": "Lahore","types": ["locality","political"]},{"long_name": "Lahore District","short_name": "Lahore District","types": ["administrative_area_level_2","political"]},{"long_name": "Punjab","short_name": "Punjab","types": ["administrative_area_level_1","political"]},{"long_name": "Pakistan","short_name": "PK","types": ["country","political"]}],"formatted_address": "Lahore, Pakistan","geometry": {"bounds": {"northeast": {"lat": 31.633287,"lng": 74.50551},"southwest": {"lat": 31.334211,"lng": 74.1469}},"location": {"lat": 31.554605,"lng": 74.357155},"location_type": "APPROXIMATE","viewport": {"northeast": {"lat": 31.633287,"lng": 74.50551},"southwest": {"lat": 31.334211,"lng": 74.1469}}},"place_id": "ChIJ2QeB5YMEGTkRYiR-zGy-OsI","types": ["locality","political"]}],"status": "OK"}'
Better View JSON
After that you just have to parse your JSON text and append the values wherever needed
HTML
<div id="test"></div>
JavaScript
var obj = JSON.parse(text);
var text_div = document.getElementById('test');
for (i = 0; i < obj.results[0].address_components.length; i++) {
text_div.innerHTML = text_div.innerHTML + obj.results[0].address_components[i].long_name + '<br>';
}
JSFIDDLE

Related

Creating a nested Json from an array

I have this Js array:
const a = [
[
"Paris",
"75000"
],
[
"Toulouse",
"31000"
],
[
"Marseille",
"13000"
]
];
How to convert restructure this array to JSON?
[{
"city": "Paris",
"zip": "75000"
},
{
"city": "Toulouse",
"zip": "31000"
},
{
"city": "Marseille",
"zip": "13000"
}]
I tried with the JSON.stringify() function but I don't get the expected result.
Thanks
Youre array declaration isn't correct. This is the correct syntax for declaring an array in JS and using JSON.stringify on it:
tab = [
{city: 'Paris', zip: '75000'},
{city: 'Toulouse', zip: '31000'},
{city: 'Marseille', zip: '13000'}
];
JSON.stringify(tab, null, 2)
You could use Array.prototype.map to convert sub-array entries of the original array into objects with suitably named properties, and call JSON.stringify on the result.
const tabs = [
[
"Paris",
"75000"
],
[
"Toulouse",
"31000"
],
[
"Marseille",
"13000"
]
];
// restructure sub-arrays into objects:
let objectArray = tabs.map(entry=> {
const [city, zip] = entry;
return {city, zip};
})
// Stringify object array
let jsonText = JSON.stringify( objectArray, null, 2)
console.log(jsonText);
The map function is using Destructuring assignment to extract city and zip values from each sub-array.
A null second and numeric third parameter supplied to JSON.stringify improve human readability of the output but are generally omitted in production environments to reduce the length of network messages.

Adding a Object Array in a Array into a JSON

I had this JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?
Please check this solution of adding objects to object property:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}';
var obj = JSON.parse(jsonStr);
obj['event']['products'].push({"name":"Blue Shirt","price":"100"});
obj['event']['products'].push({"name":"Nike Shoes","price":"150"});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
From the look of it, event is a JSON Array on its own so to target the first one you will have to pict JSON Object at index 0.
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});

Save JSON value as another JSON file

I have a JSON file like below:
{
"soils": [{
"mukey": "658854",
"mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)",
"sl_source": "Fl soil map",
"cokey": "3035468",
"soilName": "Eunola",
"comppct_r": 20,
"compArea": "9.96",
}],
"asfirs": [{
"long": -82.96896600817682,
"lat": 29.977675992923395
}],
"polygon": [{
"rings": [
[
[-9235836.910744485,
3501136.0564117758
],
[-9235798.692230342,
3500237.921329426
],
[-9236553.507884657,
3500667.87961353
],
[-9235836.910744485,
3501136.0564117758
]
]
],
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
}
}]
}
I want extract the value of Polygon key to another JSON object like below
{
"rings": [
[
[-9161396.799823288,
3453315.140590871
],
[-9160708.866568722,
3453095.3841345515
],
[-9161349.02668061,
3452751.4175072685
],
[-9161396.799823288,
3453315.140590871
]
]
],
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
}
}
Now when I do it using
var key3 = 'polygon';
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON);
where polgonJson contains my initial JSON file I get an extra [] bracket which is not allowing me to create a proper JSON file, like below.
[{
"rings": [
[
[-9235836.910744485,
3501136.0564117758
],
[-9235798.692230342,
3500237.921329426
],
[-9236553.507884657,
3500667.87961353
],
[-9235836.910744485,
3501136.0564117758
]
]
],
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
}
}]
How can I get rid of those [] brackets or extract the value properly?
When you stringify JSON object, it puts extra [] brackets because it takes your object as an array. To extract JSON from text variable, you need to get value of the first (and only) element in that array.
var key3 = 'polygon';
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON[0]);

Iterating over an array of objects?

Here is some sample data that I get from an API:
{
"Document": {
"Placemark": [
{
"name": " V5-MJW",
"address": "Aviation Road, Windhoek, Namibia",
"description": [],
"TimeStamp": {
"when": "2016-05-21T06:12:00-04:00"
},
"styleUrl": "#asset7541",
"Point": {
"coordinates": "17.0829055,-22.598271,743"
}
},
{
"name": "GSatMicro80149",
"address": "Unnamed Road, Lesotho",
"description": [],
"TimeStamp": {
"when": "2016-05-11T04:52:00-04:00"
},
"styleUrl": "#asset7543",
"Point": {
"coordinates": "27.5594894,-29.456703,1659"
}
}
]
}
}
This is my current code that is creating an array:
var flightPlanCoordinates = [];
//data being the returned values from the API.
$.each(data.Document.Placemark, function () {
var location = this.Point.coordinates.split(',');
var loc = {lat: parseFloat(location[1]), lng: parseFloat(location[0])};
flightPlanCoordinates[this.name] == null ? flightPlanCoordinates[this.name] = [] : flightPlanCoordinates[this.name].push(loc);
});
I get a lot of placemarks with the same name, I want to split each placemark with a different name into a different array.
This all works fine until I try to itterate over flightPlanCoordinates, I tried the following:
$.each(flightPlanCoordinates, function(index) {
}
But this does not work, If I log the length of flightPlanCoordinates, it results in 0, yet in Firefox Dev tools I can see the correct values inside of flightPlanCoordinates.
How would I go about doing this? Is there a better way than what I am doing here?
Please change
var flightPlanCoordinates = [];
to
var flightPlanCoordinates = {};
it should be an object, because you set it with properties like flightPlanCoordinates[this.name], where this.name is a string, not an index.

How can I remap one JSON lines to hierachycal JSON?

I am meeting now the difficult problem for me that hurt my heart,
I want to convert [01] JSON to [02].
[01] JSON :
{locations: [
{
country: "Australia",
area: "NSW",
city: "Gordon"
},
{
country: "Australia",
area: "NSW",
city: "Chatswood"
}
]};
[02] JSON :
{countries: [
{
name: "Australia",
areas: [
{
name: "NSW",
cities: [
{
name: "Gordon"
},
{
name: "Chatswood"
}
]
}
]
}
]}
Since you're going to be doing a bunch of lookups I suggest using a collection of objects rather than your final structure with arrays. You can then either convert it to the final structure or modify code to use it the way it is.
var countries = {};
for (var i=0, loc; loc = locations[i]; i++) {
if (!countries[loc.country]) countries[loc.country] = {};
if (!countries[loc.country][loc.area]) countries[loc.country][loc.area] = [];
countries[loc.country][loc.area].push(loc.city);
}
alert(JSON.stringify(countries));

Categories