Obtain a particular value from a JSON file using JavaScript

My JSON file, named json.json, contains the following data:

{"name1":"Hallo","name2":"Defy","name3":"Carm","name4":"Disney"}

To read this file, I am using the following script:

<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
$.each(person, function(key, value)
{document.write(key+"= "+value+"<br />"); 
});
});
});
</script>

Although this script displays all the data, I only want to store the value of "name3" in +value+

What modifications should I make to accomplish this?

Answer №1

Instead of iterating through, you can simply do this:

$.getJSON("data.json", function(user){
    document.write("username: " + user.username);
});

It might be better to avoid using document.write and instead append the result to a specific container.

<div id="output"></div>

$.getJSON("data.json", function(user) {
    $("#output").append("<p>Username: " + user.username + "</p>");
});

Answer №2

$.getJSON is a handy method that fetches JSON data and returns it as a JavaScript object.

If you want to access the name3 property from the retrieved object, you can easily do so using the following code snippet:

$.getJSON("data.json", function(user){
    // manipulate user.name3 as needed...
    console.log(user.name3);
}

Answer №3

If you want to access the property, simply use a dot "." notation. For example, to retrieve the value of name3, you would write value.name3.

If you only have one item, there's no need for a foreach loop.

<script type='text/javascript'>
    $(window).load(function(){
        $.getJSON("json.json", function(person){
            document.write(key + " = " + value.name3 + "<br />"); 
        });
    });
</script>

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

Using a local variable with jquery getJSON: A comprehensive guide

I am looking to expand the autocomplete capabilities of Ace Editor and I require a JSON file containing words. Here is my code snippet: function load_completions() { var object = $('#preview').attr('class'); $.ajax({ ...

Is There Vega Support for Text in HTML or Markdown?

I am looking to implement the Vega library to display text with links while also having the option to style the texts accordingly (such as headlines, emphasis, italics, dropdown). Is there a way to style text in Vega using HTML or Markdown formats? If no ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

What is the most efficient method for converting JSON to a generic Object array in Angular 2 using TypeScript?

Is it possible to convert a blob of JSON into an array of generic objects? The objects may vary based on the URL. Would JSON.parse(res.json().data) be the appropriate method to accomplish this? Thank you. return this.http.get(URL) ...

How do I detect the " * " key in a keyEvent?

if(keyEvent.keyCode == 8){ $scope.erase(); } else if(keyEvent.keyCode === 107){ console.log("+"); $scope.inputToCal('+') } else if(keyEvent.keyCode === 109){ console.log("-"); $scope.inputToCal('-&ap ...

Counting down in JavaScript until the desired MySQL datetime format is reached

I'm trying to display a countdown of hours and minutes to a date pulled from a MySQL database in the format 2010-09-24 11:30:12. I am not well-versed with dates in JavaScript, so any guidance would be greatly appreciated. Thank you. ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

Sorting JSON data in EJS based on categories

Hello, I am facing a dilemma. I need to apply category filtering to a JSON file but I am unsure of how to proceed with it. For instance, I wish to filter the 'vida' category along with its description and price. I seem to be stuck at this junctu ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

React - The protocol "https:" is not supported. The expected protocol is "http:"

Yes, I came across this particular post, but I don't have a file where I can make edits to switch to using https, and my backend runs on ASP.NET MVC Core 3.1. When my React application makes API calls to the ASP.NET MVC application, it throws an erro ...

Retry an Ajax request immediately after a timeout without having to wait for the full

I am attempting to resend an AJAX request every 5 seconds if there is an issue, but when I simulate an offline connection with Chrome, the AJAX request doesn't wait 5 seconds between each attempt and keeps getting called continuously. What could be c ...

Validating object keys

I am dealing with an array of objects and I need to find a way to pass multiple keys in the function checkArray to validate these keys within each object. var test = [ { // Object details here... }, { // Another object details here... } ...

Javascript code to verify whether the page is currently positioned at the top

How can I use JavaScript to determine if the page is at scroll(0,0)? I have a full-page slider that needs to pause when the page is no longer at the top. The page may not be scrolled manually, as there are internal HTML # links that could load the page d ...

Message indicating NoteContext is not defined

In my React project, I first created a NoteContext and then initialized an array using the useState hook. This array was imported into the Notes component where I used .map to display the titles of the objects in the array. However, when running the code, ...

Encountered issues loading JavaScript and received a pyppeteer error while trying to access a website through requests

I am facing a challenge when trying to scrape a webpage post login using BeautifulSoup and requests. Initially, I encountered a roadblock where the page requested JavaScript to be enabled to continue using the application. To work around this issue, I de ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Placing a pin on the map: AngularJS

Struggling to grasp AngularJS and its mapping capabilities has been quite challenging for me. Currently, my code looks like this: <map data-ng-model="mymapdetail" zoom="11" center="{{item.coordinates}}" style="heigth:375px"> <div ...

Having trouble retrieving the value of an object within an array

{"-L0bFExUeZXB3-MUXCda":{"Comment":"GOOD","Date":"18 December","User":"OlaNord"}} {"-L0bFCJh5SPUOWMjTRKu":{"Comment":"ok","Date":"18 December","User":"OlaNord"}} {"-L0bFA2uzsGDizxxzN1p":{"Comment":"wewwe","Date":"18 December","User":"OlaNord"}} With ...

Tips for Sharing Multiple Nested Arrays in AngularJS

I am working with an array in AngularJS, and here is an example: $scope.order.qty='20'; $scope.order.adress='Bekasi'; $scope.order.city='Bekasi'; To post this array, I use the following code: $http({ method : &ap ...

Guide to creating a vertical handler that can be resized

Did you know that you can resize tables in http://www.jsfiddle.net? I'm curious about how to resize just the "Vertical Handler". Could someone share the source code with me? If possible, please provide an example on http://www.jsfiddle.net. ...