0

I have a string that looks like the following:

 {
 "results": [
 {
 "address_components": [
 {
 "long_name": "Ireland",
 "short_name": "Ireland",
 "types": [
 "establishment",
 "natural_feature"
 ]
 }
 ],
 "formatted_address": "Ireland",
 "geometry": {
 "bounds": {
 "northeast": {
 "lat": 55.38294149999999,
 "lng": -5.431909999999999
 },
 "southwest": {
 "lat": 51.4475448,
 "lng": -10.4800237
 
 }
 }],
 "status" : "OK"
 }

I want to turn this into a json that I can easily traverse. However when I call JSON.parse() on this string I get a json array that is a pain to traverse. I want to be able to extract the lat and lng from northeast without having to loop through the entire array.

asked Jan 13, 2022 at 20:03
6
  • What do you mean by turn it into a JSON? If it's a string, it's already a JSON. If you parse it, you get an object, not a JSON. Commented Jan 13, 2022 at 20:04
  • What if there are multiple elements in the results array? How will you get all the lat and lng without looping? Commented Jan 13, 2022 at 20:05
  • 1
    There is one single item in the array. You can just use [0]. If there is more than one item, you will have multiple lat/long values anyway, so you'd need iteration of some description. Commented Jan 13, 2022 at 20:05
  • If the result key is an array I cannot figure another way to do it without a loop Commented Jan 13, 2022 at 20:06
  • object.results[0].geometry.bounds.northeast.lat Commented Jan 13, 2022 at 20:06

1 Answer 1

1
 var json = `{
 "results": [
 {
 "address_components": [
 {
 "long_name": "Ireland",
 "short_name": "Ireland",
 "types": [
 "establishment",
 "natural_feature"
 ]
 }
 ],
 "formatted_address": "Ireland",
 "geometry": {
 "bounds": {
 "northeast": {
 "lat": 55.38294149999999,
 "lng": -5.431909999999999
 },
 "southwest": {
 "lat": 51.4475448,
 "lng": -10.4800237
 }
 }
 }
 }
 ],
 "status" : "OK"
}`;
var data = JSON.parse(json);
var bounds = data.results[0].geometry.bounds;
var bound = bounds.northeast || bounds.southwest;
console.log(bound.lat, bound.lng);

If you know northeast is always an option you can simplify this to:

console.log(data.results[0].geometry.bounds.northeast);

That will give you your lat and lng.

answered Jan 13, 2022 at 21:10
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.