Importing JSON data into JavaScript

For the past few hours, I've been attempting to load a JSON file into JavaScript to feed map coordinates to the Google Maps service.

Unfortunately, my script is incomplete and I cannot obtain any results. Here's what I have so far:

<script>
 function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'http://127.0.0.1/irismaps/aitems.php', true); // path to file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Since .open does not return a value in asynchronous mode, use an anonymous callback here
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

function init() {
 loadJSON(function(response) {
  // Parse JSON string into object
    results = JSON.parse(response);


                 for (var i=0; i<results[0].markers.length; i++) {
            for (var b=0;b<results[0].markers[i].length;b++) {

                    // The desired object
                    console.log(results[0].markers[i]);
                    break;

            }



    }
 });
}
</script>

JSON:

{
  "results": [
    {
      "markers": [
        {
          "longitude": "37.66653612499999",
          "latitude": "55.77875861131171",
          "title": "Industry LLC",
          "icon": "img/markers/shop.png"
        },
        ...
        OMITTED FOR BREVITY
        ...
        {
          "longitude": "-115.20111025",
          "latitude": "55.80752971122906",
          "title": "Book Group Inc.",
          "icon": "img/markers/shop.png"
        }
      ]
    }
  ]
}

Answer №1

Consider this approach:

results.results[0].markers[i]

The code snippet is utilizing an object named results which includes an array also named results.

Answer №2

The data in the JSON file you are attempting to load is essentially JavaScript code. Assign a name to your object, like:

var myJSONObject = {
    "key": "value"
};

Save this code as a .js file and then import it into your document.

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

JavaScript does not function properly when interacting with the result of a POST request made through $.ajax

Question: After including jQuery files and functions in index.php, do I also need to include them in select.php? To clarify my issue, here is the problem I am facing: Initially, I am trying to send data to select.php using jQuery's $.ajax. The data ...

``What is the best way to handle CRUD operations in an Express application?

I have implemented node.js, express, and MongoDB connection with mongoose. Originally, I had a working code in a single file called server.js without using express. However, upon trying to integrate it into express, the functionality is not as expected. T ...

Verify if the nested JSON object includes a specific key

Currently, I am grappling with a dilemma on how to determine if within a deeply nested JSON object, featuring numerous unknown arrays and properties, lies a specific property that goes by the name "isInvalid". My objective is to identify this property and, ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

Generating JSON files for multiple children

I'm still learning about JSON and could use some guidance. When I first imported our database, everything seemed to work fine: { "Audi":[ "80", "100", ], "Bentley":[ "Azure", "(C)", ] } Now we're looking ...

I am having trouble creating a Choropleth Map with my code. Any guidance would be greatly appreciated

Encountering an error message that reads: The choropleth method is no longer supported and deprecated. Utilize the new Choropleth class with similar arguments instead. Refer to the 'GeoJSON_and_choropleth' example notebook for guidance. with ope ...

Selenium IDE fails to load web pages that generate a JSON response

My extensive Selenium test suite is designed to test a web service by providing an input URL, which in turn generates either a standard HTML response or a JSON response. Currently, the tests are being executed using Firefox's Selenium IDE. The tests i ...

Issue with using Javascript variables within Highcharts

I am facing an issue with displaying a high charts pie chart dynamically. When I pass the exact value format into the data index in the high chart, it doesn't show anything in the chart. However, if I directly assign a value to a variable, it works fi ...

Issue with JQuery: object.id is returning as undefined even though it should have a value

While working with JQuery, I encountered a rather peculiar (or possibly foolish) error. The HTML code snippet in question is as follows: <input type="password" name="repeatPassword" id="id_repeatPassword" /> And within my javascript code, I have t ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...

What is causing npm to search for the package.json file in the incorrect directory?

I am currently working on a web application using TypeScript, Angular, and various dependencies. Of course, npm is also an essential part of the project. The package.json file was initialized in the project from the beginning using npm init, and it current ...

Difficulty in sharing cookies among subdomains

I have successfully stored my visitors' style sheet preference in a cookie, but I am facing an issue with sharing the cookie across subdomains. Even after specifying the domain, the cookie does not seem to be shared. What could be causing this proble ...

Does the TS keyof typeof <Object> rule prohibit the assignment of object.keys(<Object>)?

I'm having trouble understanding the issue with this code snippet. Here is the piece of code in question: export type SportsTypes = keyof typeof SportsIcons export const sports: SportsTypes[] = Object.keys(SportsIcons); The problem arises when I at ...

When I attempt to incorporate multiple sliders on a single page, I encounter difficulties in determining the accurate stopping position if the number of slides varies

I am having trouble setting the correct stop position for sliders with different numbers of slides on a page. When I have the same number of slides in each slider, everything works fine. However, I need to have a different number of slides in each slider ...

Attention: certain content may have been removed due to HTML sanitation

Hi there, I'm currently working on incorporating a search bar into a modal window by embedding HTML within the modal body. Here's how I've written the code: onClick() { const dialogRef = this.modal.alert() .size('lg' ...

How can you optimize the uploading time and bandwidth by a factor of 1/3 when the output of toDataURL is in base64 format?

The purpose of the code snippet below is to compress a 2 MB JPG file to a 500 KB file, and then upload it to a server upon submitting a <form>. By importing an image from a JPG file into a canvas and exporting it using toDataURL, the following JavaS ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

Encountering a problem with server-side jQuery autocomplete

I attempted to utilize a customized service I created in order to make this jquery autocomplete example work, but unfortunately it's not functioning properly. Here is the code snippet: $( "#city" ).autocomplete({ source: function( request, res ...

Usage of Firebase data

Looking for assistance on how to retrieve data from Firebase Cloud Store. My code includes the Firebase configuration and app.js but I'm facing an issue where the page appears blank on localhost:3000 without any errors. Below is the firebase.js confi ...

The functionality of the delete button in Datatables is only operational on the initial page, failing to

My datatable is giving me trouble. The delete button in the action column only works on the first page, but not on the other pages. Here is the code for my delete button: <table id="example" class="table table-striped table-bordered" cellspacing="0" wi ...