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

What are the benefits of using .factory instead of declaring a variable in AngularJS?

As I delve into learning Javascript and Angular JS, I'm exploring alternative approaches to using .factory. Instead of declaring what it returns as a variable and referencing it, I'm curious if there's a way around using factory. Why is fac ...

Launch a fresh fancybox once the previous one has exited

I am currently facing an issue with my password change process through a fancybox window. Whenever a user enters the wrong password, a "Wrong Password" iframe opens up. However, the challenge arises when I try to reopen the "Password Change" iframe after c ...

Reorder the sequence of the JSON array

Hello, I am currently working on a project using CodeIgniter and have encountered an issue that I need help with. Here is the problem I'm facing: I have an array generated in PHP: Array ( [0] => Array ( [0] => 3 ...

The array does not store the ObjectId

I'm trying to implement the favoriting feature following a tutorial, but I'm encountering issues with making it work. Any assistance would be greatly appreciated. Thank you! UserSchema: var UserSchema = new mongoose.Schema({ username: {type ...

Swapping out the initial icon in a v-list-item with Vuetify

I have a list of items with icons that need to change when clicked. The issue I am facing is that all icons are changing at once because they share the same v-model. How can I modify my code so that only the icon being clicked changes? Here is my current i ...

Error: React JS is unable to access the property 'path' because it is undefined

Currently, I am encountering an issue while setting the src of my image in React to this.props.file[0].path. The problem arises because this state has not been set yet, resulting in a TypeError: Cannot read property 'path' of undefined. To provid ...

Storing a pair of distinct data fields in a c# Array Json from a Class

Greetings! I have been working on a code snippet where I define all the necessary classes to create a JSON string for a put request. My goal is to include both the AttributeColor and AttributeSize fields in the attributes array so that the JSON output look ...

Routes inoperative as intended

When using a standard expressroute for this login, I have noticed that even if the req.body.password is incorrect, I am still getting redirected to '/login'. router.post('/student/login', (req, res) => { if (req.body.password === ...

Tips for identifying emails from protected platforms such as ProtonMail or Hushmail

A question for the community: So, I have a website that's totally above board and legitimate. Lately, I've noticed some shady characters trying to register from email domains like Proton and Hush - yikes! Before I dive into PhoneText validation, ...

Storing data from a massive JSON array into a separate array using a specific condition in JavaScript

Dealing with a large JSON array can be challenging. In this case, I am looking to extract specific objects from the array based on a condition - each object should have "dbstatus":-3. data = [{"id":"122","dbstatus":-3},{"id":"123","dbstatus":"-6"},{"id" ...

The AngularJS directive within a directive is failing to properly initialize the scope value

In my current setup, I am working with a controller that contains the value $scope.colorHex. As an example, I am utilizing the directive colorpickerTooltip, and within its template, I am calling another directive: <colorpicker ng-model="colorHex">&l ...

Unforeseen outcomes arise when toggling expansion in JavaScript

I have a pop-out div at the top of my page that expands and closes on toggle. Also, when I toggle the pop-out div, it changes the top position of another div (a side pop-out menu). The issue is that the side pop-out menu should only appear when clicking ...

What is the method to determine the overall size of a webpage using the Google PageSpeed API?

"analytics": { "cssResponseBytes": "333 kB", "htmlResponseBytes": "269 kB", "imageResponseBytes": "3.35 MB", "javascriptResponseBytes": "2.29 MB", "numberCssResources": 2, "numberHosts": 80, "numberJsResources": 72, "numberR ...

PHP and MySQL with jQuery and AJAX combine to create a real-time news feed update system similar to Twitter

Is there a way to automate the news feed on my website so that it periodically checks for new status updates? I would like it to display a button labeled "(?) New Messages" when there are new updates, and then load only the new ones when the button is clic ...

Automatically Refresh a Div Element Every 5 Seconds Using jQuery's setInterval() Function

My goal is to refresh the left div every 5 seconds using $.ajax to get JSON data and display 4 random elements in that div. However, even though the left div block refreshes, the content remains the same with the same images always showing. view image desc ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

UTF-8 Encoding of Quotation Marks in Android

Within my Android app, I have implemented the utf-8 charset to retrieve JSON data from a server. The code snippet below showcases how I encode the data received from the server: try { HttpResponse execute = client.execute(httpGet); ...

Showing VUE Content Delivery Network

Unable to render v-for with CDN in Vue.js const Gallery = { template: '{{$t('gallery')}} <img :class="[[item.class]]" v-for="(item, index) in carousel" :src="[[item.img]]" alt="img" />' } c ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

"Can you provide instructions on how to set the background to the selected button

How can I change the background color of a selected button in this menu? Here is the code for the menu: <ul id="menu"> <li class="current_page_item"><a class="button" id="showdiv1"><span>Homepage</span></a></ ...