Collect JSON data with [] from Javascipt

0

I want to raise a problem that I have and I do not see an apparent solution on the internet. I have an .json file with this format:

[{"id":"hola"}, {"id":"adios"}]

When I want to collect this data in JS like I do

var id= JSON.parse(AQUI QUE PONGO);

I know if in the json file I put a name to the array and then I apply JSON.parse works for me. But I do not want to do it this way. Thanks and regards

    
asked by jose 02.06.2018 в 15:46
source

3 answers

0

This would be a good way:

let myvar = [{"id":"hola"}, {"id":"adios"}];

for(i in myvar){
	let current = myvar[i].id;
	console.log(current);
}

And so you can do with objects that contain more properties, for example:

[{"id":"hola", "nombre": "juan", "numero": 1}, {"id":"hola", "nombre": "pedro", "numero": 2}];

let myvar = [{"id":"hola", "nombre": "juan", "numero": 1}, {"id":"hola", "nombre": "pedro", "numero": 2}];

for(i in myvar){
	let current = myvar[i];
	console.log(current.nombre);
	console.log(current.numero);
	//etc ...
}

This is so because what you have is an array of objects, for example:

          let o1 = {'id':"hola", 
                    'nombre': "juan", 
                    'numero': 1};

that can be added to the Array like this:

let myArray = [];
myArray.push(o1);

and execute the operations that I have described above.

    
answered by 02.06.2018 в 16:50
0

Analyzing a bit your question reach this conclusion, you want to show a Data in a file JS of a file .JSON for this I would do the following:

1- Request HTTP to bring the data I need:

script.js

function loadXMLDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var res = this.responseText;
            var converRes= JSON.parse(res);
            alert(converRes[1].id);
        }
    };
    xhttp.open("GET", "data.json", true);
    xhttp.send();
}

data.json

[{
    "id":"hola"
}, {
    "id":"adios"
}]

As you can see in the function javascript I make a request where I have a variable called res where I store the objeto in text format, then I have a variable called converRes where I convert the text string in objeto I need and then I do the alert with the id I want, in this case "id":"adios"

I hope this answer serves you and if it is what you need, I remain pending before any question ...

    
answered by 02.06.2018 в 17:22
0

is easy, your structure is based on an array [object], you can simply go through it with each of jQuery and then read its indices inside:

link: link

practical example:

$.each(JSON.parse('[{"id":"hola"}, {"id":"adios"}]'), function( index, value ) {
  console.log( index + ": " + value.id );
});

run it in console, once you have loaded the jQuery api.

greetings

    
answered by 02.06.2018 в 17:25