Create a JSON in Javascript

5

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 tested 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 do not know if I'm accessing correctly, I do not control a lot of 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 speeds I want in the Json and parsing that matrix

    
asked by Silvia 26.03.2018 в 18:37
source

3 answers

7

You must take into account that a hierarchical structure must be created and then the resulting object will be the value to be printed

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 datos  = [];
var objeto = {};

for(var i= 0; i < arrayNombres.length; i++) {

    var nombre = arrayNombres[i];

   datos.push({ 
        "nombre"    : arrayNombres[i],
        "apellido"  : arrayApellido[i],
        "ciudad"    : arrayCiudad[i] 
    });
}

objeto.datos = datos;
console.log(JSON.stringify(objeto));

$("#res").text(JSON.stringify(objeto));
    
answered by 26.03.2018 / 19:46
source
4

The logic you use to push an object var obj = JSON.parse(json); is not what you should do is declare it in the way I point below. In addition to this there are other ways such as list['datos'].push() if I do so is to have a better order when you declare the object attributes.

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";

// esta deberia ser la forma en la cual declaras tu objeto datos para que la pueda parsear a Json
var list = {
  'datos' :[]
};

//guardas los datos
for (var i = 0; i < arrayNombres.length; i++) {

    list.datos.push({
    "nombre": arrayNombres[i],
    "apellido": arrayApellido[i],
    "ciudad": arrayCiudad[i]
  });
};

json = JSON.stringify(list); // aqui tienes la lista de objetos en Json
var obj = JSON.parse(json); //Parsea el Json al objeto anterior.

$("#res").text('' + json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="res"> nada</span>
    
answered by 26.03.2018 в 19:42
3

Hello the problem is that you are misinterpreting the functions JSON.stringify and JSON.parse

A JSON explaining it is simply a string with a certain format, with JSON.parse(string) you convert that string into an Object or Array Javascript, with JSON.stringify(obj) you do the inverse operation of converting a JavaScript object to a formatted string.

The problem in your code is the following

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);

the first line var obj = JSON.parse(json); is not necessary, the variable json is a javascript object, not a string, so it will give an error.

so the cycle for would be like this:

for (var i = 0; i < arrayNombres.length; i++) {
    json['datos'].push({"nombre":arrayNombres[i],"apellido":arrayApellido[i],"ciudad":arrayCiudad[i]});
};

The following line json= JSON.stringify(obj); converts the array to a JSON string but it would generate error in the following line, so it must be omit in summary so it should be:

// var obj = JSON.parse(json);
for (var i = 0; i < arrayNombres.length; i++) {
    json['datos'].push({"nombre":arrayNombres[i],"apellido":arrayApellido[i],"ciudad":arrayCiudad[i]});
};
// json= JSON.stringify(obj);
$("#res").text(''+ json.datos[1].nombre);
    
answered by 26.03.2018 в 19:35