Storing JSON information within a variable

I'm currently working on an autocomplete form that automatically populates the location field based on the user's zipcode. Below is the code snippet I've written to retrieve a JSON object containing location information using the provided zipcode:

var client = new XMLHttpRequest();
client.open("GET", "http://api.zippopotam.us/nl/1012", true);
client.onreadystatechange = function() {
    if(client.readyState == 4) {
        // alert(client.responseText);
        var jsonObj = [client.responseText]

    };
};

client.send();

My challenge now is to extract only the location data from the JSON response and store it in a variable. What I want to achieve is something like this:

var location = 'Amsterdam'

Any suggestions or tips would be greatly appreciated. Thank you!

Answer №1

After examining the result of a GET request to http://api.zippopotam.us/nl/1012, here is the output:

{
    "post code" : "1012",
    "country" : "Netherlands",
    "country abbreviation" : "NL",
    "places" : [{
            "place name" : "Amsterdam Binnenstad en Oostelijk Havengebied",
            "longitude" : "4.9027",
            "state" : "Noord-Holland",
            "state abbreviation" : "NH",
            "latitude" : "52.3666"
        }
    ]
} 

To extract specific data from this response, you can utilize the following code snippet:

var jsonResponse= JSON.parse(client.responseText);
var locations=jsonResponse.places; //an array!
if (places.length) {
  var firstLocation=locations[0]['place name'];
}

Answer №2

Can you please share the XML request response that you received? To extract data from a JSON object using JavaScript, you can do the following:

var jsonData = JSON.parse(jsonObject)

Then, you can access specific values from the JSON object like this:

var name = jsonData['name']

Make sure to replace name with the actual key value you are trying to retrieve from the JSON data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the presence of when I JSON encode an array?

While I'm in the process of creating arrays and converting them into JSON strings, I came across an unusual issue. Some of the strings are unexpectedly adding \r\n at the beginning and end when I encode them to JSON format. These particular ...

Unable to interpret Python/Django-generated JSON object on client side

I'm encountering an issue while passing a data object from a Python/Django application to the frontend using AJAX in JSON format. Despite everything appearing to be functioning correctly, I am unable to properly parse the JSON object within JavaScript ...

I must extract all the information from the webpage within the HTML tags, however, I am unsure of which specific tag to target for the data extraction

Here is the example of HTML code that includes a price: <meta itemprop="price" content="121080"> I have created this search code, but I am unsure which tag to use for finding the price: const puppeteer = require('puppeteer&a ...

How can we bring in a function into a Vue component?

I'm currently facing an issue with importing a single function into my Vue component. To tackle this problem, I separated the function into its own js file: randomId.js: exports.randomId = () => //My function ... Within my Vue component, I attem ...

The size of the .json file exceeds the limit for opening in R using rjson

I'm facing a data challenge with a hefty 5.1 GB json file that I'm struggling to read in R using rjson. My ultimate goal is to create a dataframe from it, but the sheer size seems to be causing obstacles in loading it successfully. Do any of you ...

I am unable to make changes to the Text Field component in Material-UI

After developing a React App using Material-UI, I decided to create independent Components. Below are the independent components (<PanelDiv/>): render() { return ( <div className="panelDiv-component" style={{display:this.prop ...

React hooks causing dynamic object to be erroneously converted into NaN values

My database retrieves data from a time series, indicating the milliseconds an object spends in various states within an hour. The format of the data is as follows: { id: mejfa24191@$kr, timestamp: 2023-07-25T12:51:24.000Z, // This field is dynamic ...

Obtain a report using a variety of different conditions

My database has a table with the following fields: TPI CLICKS IMPRESSION CLASSIFY I am looking to retrieve 3 specific results: 1) Calculate SUM(CLICKS)/SUM(IMPRESSION) * 100 GROUPED BY TPI 2) Calculate SUM(IMPRESSION) WHERE CLASSIFY = "XYZ" GROUPED BY ...

Activate the date-picker view when the custom button is clicked

Utilizing this library for date-picker functionality has been quite beneficial. I am currently working on a feature that involves opening the date-picker upon clicking a custom button. The default input is functioning properly. <input name="pickerFromD ...

What could be causing the partial to not load JavaScript properly?

Hello, I am a newcomer to Angular and I'm currently working on implementing the slick carousel. It functions properly on the index page, but when I try to use the same HTML in a partial and include it with ng-view, it doesn't work as expected. T ...

I require assistance in consolidating multiple arrays retrieved from a JSONP request into a single unified array

My goal is to gather all viewers (people in chat) from a specific channel on Twitch and store them in an array. Although the JSONP call is functioning, the Twitch API provides multiple arrays: moderators staff admins global_mods viewers The plan is to ...

Guide to incorporating a JSON file parsing method in Java

I am attempting to extract the data from a JSON file named text.json using the Jackson library. My goal is to create a Java method within the provided code that can retrieve all keys and values from the JSON file. However, my current implementation only f ...

A TypeScript method for accessing deeply nested properties within an object

I'm currently working on a function that utilizes typings to extract values from a nested object. With the help of this post, I managed to set up the typing for two levels successfully. However, when I introduce a third (known) level between the exis ...

What is the best way to format my JSON data from an API response that includes linebreaks?

Currently, I am encountering an issue while trying to communicate with the isbndb.com API. Despite successfully receiving a response, the JSON string that I obtain contains special characters for line breaks, making it impossible to deserialize the data. T ...

The object in question does not have the capability to support the "live" property or method

I've encountered an issue in IE related to a script error with the live method. The problem arises when testing on the website URL @ Despite trying multiple solutions and various fixes, I haven't been able to resolve the issue yet. Any assistanc ...

show a notification once the maximum number of checkboxes has been selected

I came across this code snippet from a previous question and I'm interested in making some modifications to it so that a message can be displayed after the limit is reached. Would adding a slideToggle to the .checkboxmsg within the function be the mos ...

When the response is anything other than a String, the afterCompletion method of the HandlerInterceptor interface is executed prior to the response being completely committed

While troubleshooting an issue, I encountered a peculiar situation in my Spring Boot application. I have a GET REST endpoint that returns a specific POJO: @GetMapping(value = "/dto", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseE ...

Transform a dictionary into a personalized JSON object using C#

I've been mulling over this issue for hours now and I just can't seem to figure it out. I'm really hoping someone can point me in the right direction. The challenge I'm facing is converting a Dictionary object into a JSON format. Belo ...

Breaking down JSON data frames into various columns in R

I have a JSON file that I need to process data = readLines("D:/aaa/bbb/ccc/ddd.json") data = lapply(data, fromJSON) data = lapply(data, unlist) result = bind_rows(data) Upon processing the JSON file with readLines method, I obtained this result: ...

Guide to adding customized CSS and JavaScript to a specific CMS page on Magento

I'm trying to incorporate a lightbox for video playback on a specific page of my CMS. I've placed my CSS file in JS/MY THEME/JQUERY/PLUGIN/VENOBOX/CSS/myfile.css and the JS files in JS/MY THEME/jquery/plugins/venobox/js/myfile.js, but it doesn&ap ...