1

I am trying to read from a JSON file into a PHP array and then echo the array's content, so I can fetch the info with ajax in javascript and convert the array in javascript to an array of JSON objects.

Here is how my JSON file looks like.

[["{\"id\":1474541876849,\"name\":\"D\",\"price\":\"12\"}"],["{\"id\":1474541880521,\"name\":\"DD\",\"price\":\"12\"}"],["{\"id\":1474541897705,\"name\":\"DDDGG\",\"price\":\"124\"}"],["{\"id\":1474541901141,\"name\":\"FAF\",\"price\":\"124\"}"],["{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]]

Here is my php :

<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true);

$arr = array();
foreach ($json_a as $key) {
    array_push($arr,$key[0]);


}
foreach ($arr as $key) {
    echo $key;
}
?>

And this is what I am getting on the client side :

{"id":1474541876849,"name":"D","price":"12"}{"id":1474541880521,"name":"DD","price":"12"}{"id":1474541897705,"name":"DDDGG","price":"124"}{"id":1474541901141,"name":"FAF","price":"124"}{"id":1474543958238,"name":"tset","price":"6"}

It looks like I am not that far, but what can I do so I can actually make this a JSON object?

Please help!

user1866925
  • 338
  • 2
  • 9
  • just concatenating several json-strings does not, in return, give you a valid json string. have you tried using `json_encode` for this instead? – Franz Gleichmann Sep 22 '16 at 13:09
  • 1
    just use `echo "[".implode(",", $arr)."]";` – Maxx Sep 22 '16 at 13:12
  • Yes, I tried using json_encode, @FranzGleichmann . It gives me a result like this (and yes, it is without a closing square bracket): ["{\"id\":1474541876849,\"name\":\"D\",\"price\":\"12\"}","{\"id\":1474541880521,\"name\":\"DD\",\"price\":\"12\"}","{\"id\":1474541897705,\"name\":\"DDDGG\",\"price\":\"124\"}","{\"id\":1474541901141,\"name\":\"FAF\",\"price\":\"124\"}","{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]{"id":1474541876849,"name":"D","price":"12"}{"id":1474541880521,"name":"DD","price":"12"}{"id":1474541897705,"name":"DDDGG","price":"124"} – user1866925 Sep 22 '16 at 13:18

1 Answers1

1

The problem is that you have JSON inside JSON.

you have to decode twice:

<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true); //here you turn a JSON-string into an array containing JSON-strings

$arr = array();
foreach ($json_a as $key) {
    array_push($arr,json_decode($key[0],true)); //and here you turn each of those JSON-strings into objects themselves


}

echo json_encode($arr);

gives me this:

[{
    "id": 1474541876849,
    "name": "D",
    "price": "12"
}, {
    "id": 1474541880521,
    "name": "DD",
    "price": "12"
}, {
    "id": 1474541897705,
    "name": "DDDGG",
    "price": "124"
}, {
    "id": 1474541901141,
    "name": "FAF",
    "price": "124"
}, {
    "id": 1474543958238,
    "name": "tset",
    "price": "6"
}]

which is valid JSON itself and probably what you want.

Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30