user1866925 user1866925 - 2 months ago 7
JSON Question

Unable to read properly from JSON file with php

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!

Answer

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.