Get a json from php to use it in javascript


For example:

     {a:56, b:"nombre1"},
     {a:26, b:"nombre2"},
     {a:16, b:"nombre3"}

Inside data: [....] I want to add the objects.

In the php I use, I have:

echo json_encode($array, JSON_FORCE_OBJECT);

But it does not work for me.

asked by Benjamin 17.03.2018 в 04:51

2 answers


In this case you should not use JSON_FORCE_OBJECT , because if it is an associative array, you will create a json with numerical indexes whose reading will be possibly more complicated.

If you only use echo json_encode($array); you will get a JSON Array similar to this one:

    "a": 56,
    "b": "nombre1"
}, {
    "a": 26,
    "b": "nombre2"
}, {
    "a": 16,
    "b": "nombre3"

Which you can read very easily after having parseado.

For example:

var arrJson=
'[{"a":56, "b":"nombre1"},{"a":26, "b":"nombre2"},{"a":16, "b":"nombre3"}]';
var myJson = JSON.parse(arrJson);

  console.log('A: ' + item.a);
  console.log('B: ' + item.b);
answered by 17.03.2018 / 14:25

Hello benjamin, look if you have an array of data in php, just by coding it, you can use it for example

echo json_encode($array); y listo,

to use it in js you have to pass it to an object and you make it a parse so look

obj = JSON.parse(data);

and Ready with that you can use it.

answered by 17.03.2018 в 06:10