1

I am developing a mapping tool, and I am using jQuery to download JSON data from a server. the code for the jquery is currently:

$.getJSON("start.json", function(data) {
    var items = [];

    $.each(data, function(key, val) {
        alert("data: " + key + "->" + val);
    });
});

the json file looks like this:

{
    "type"  :   "obstacle",
    "top"   :   20,
    "left"  :   10,
    "height":   50,
    "width" :   70,
    "tall"  :   10
}

now, the "problem" is that, as it can be seen clearly, in this format, the json can only contain one object. how do I have to structure my file (and consequently my jquery) to have more than one object?

Thanks in advance.

1
  • Have a look at NDJSON, Newline Delimited JSON. Commented Aug 23, 2022 at 15:53

2 Answers 2

1

You can make an array of JSON objects like this:

[
    { 
        "type"  :   "obstacle", 
        "top"   :   20, 
        "left"  :   10, 
        "height":   50, 
        "width" :   70, 
        "tall"  :   10 
    } ,
    { 
        "type"  :   "obstacle", 
        "top"   :   50, 
        "left"  :   10, 
        "height":   50, 
        "width" :   20, 
        "tall"  :   10 
    } 
]

Edit: jQuery would be something like:

$.each(data, function(index, obstacle))
{
    $.each(obstacle, function(key, val) { 
        alert("data: " + key + "->" + val); 
    }); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

I am getting an alert with: data: 0->[object Object]
0

You can use an array to store them:

{
  "objects": [
    {
      "type"  :   "obstacle",
        "top"   :   20,
        "left"  :   10,
        "height":   50,
        "width" :   70,
        "tall"  :   10
      }, {
      "type"  :   "obstacle",
        "top"   :   20,
        "left"  :   10,
        "height":   50,
        "width" :   70,
        "tall"  :   10
      }, {
      "type"  :   "obstacle",
        "top"   :   20,
        "left"  :   10,
        "height":   50,
        "width" :   70,
        "tall"  :   10
      }
    ]
}

Now, when you iterate, you can access an individual object's properties:

$.each(data.objects, function(key, val) {
  console.log(key + ' => ' + val);
});

2 Comments

great! what about the jquery?
Well, data.objects will be an array that stores all of the objects. Iterate over it and console.log() some stuff.

Your Answer

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