I have some data in some arrays in Javascript and I want to go through those arrays and put the values in a Json, I am trying this code and I am not able to create the Json. To check if I have created it I am trying to print a value in
<span id="res"> nada</span>
But I don't know if I'm accessing correctly, I don't control much Javascript.
var arrayNombres= new Array();
var arrayApellido= new Array();
var arrayCiudad= new Array();
arrayNombres[0]= "nombre1";
arrayNombres[1]= "nombre2";
arrayNombres[2]= "nombre3";
arrayApellido[0]= "ape1 ";
arrayApellido[1]= "ape2";
arrayApellido[2]= "ape3";
arrayCiudad[0]= "ciudad1";
arrayCiudad[1]= "ciudad2";
arrayCiudad[2]= "ciudad3";
var json={datos:[{nombre :''},{apellido:''},{ciudad:''}]};
var obj = JSON.parse(json);
for (var i = 0; i < arrayNombres.length; i++) {
obj['datos'].push({"nombre":arrayNombres[i],"apellido":arrayApellido[i],"ciudad":arrayCiudad[i]});
};
json= JSON.stringify(obj);
$("#res").text(''+ json.datos[1].nombre);
The structure I want the Json to have is
{
datos[
{"nombre":"", "apellidos":"", "edad":""}
{"nombre":"", "apellidos":"", "edad":""}
...
]
I have also thought about creating an array with all the values that I want in the Json and parsing that array
You must take into account that a hierarchical structure must be created and then the resulting object will be the value to print
Hello, the problem is that you are misinterpreting the functions
JSON.stringify
andJSON.parse
A JSON explaining it simply is a string with a certain format, with
JSON.parse(string)
you convert that string into a Javascript Object or Array, withJSON.stringify(obj)
you do the reverse operation of converting a javascript Object to a formatted string.The problem in your code is the following
the first line
var obj = JSON.parse(json);
is not necessary, the variablejson
is a javascript object not a string so it will give an error.so the loop would look like this
for
:The next line
json= JSON.stringify(obj);
converts the array to a JSON string but it would generate an error on the next line, so it should be omitted in summary, so it should be:The logic that you use to push an object
var obj = JSON.parse(json);
is not correct, what you must do is declare it in the way that I indicate below. In addition to this there are other ways likelist['datos'].push()
if I do it like this it is to have a better order when you declare the object attributes.