0

I am trying to send JSON information from Python to PHP through a JSON file data.json, based on the content of the Stack Overflow question/answer here. I am running this code all on an Apache web server on Raspberry Pi 3.

Here is my code:

Python

import sys, json, random # I know I don't need sys and random to run this, but I was using these in my previous code.
data = {'fruit':['oranges', 'apples', 'peaches'], 'age':12}
with open('data.json', 'w') as outfile:
    json.dump(data, outfile)

When run, this program worked fine and exited with code 0.

JSON file

{"age": 12, "fruit": ["oranges", "apples", "peaches"]}

As you can see, my Python worked perfectly and the output is identical to the data variable in my python code. On second thought, the order is backward, although I don't think this matters.

PHP

Now, this is where the problem is:

<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a as $key) {
    array_push($arr,json_decode($key[0],true));
}
echo json_encode($arr);
?>

When run, the program exited with code 0 but outputed:

[null,null]

Does anyone have an idea why this is, or is this just the way JSON works?

cs95
  • 379,657
  • 97
  • 704
  • 746
Tiskolin
  • 167
  • 17
  • 1
    json_decode is only valid on JSON strings and the json_decode's in the loop are not given JSON strings: the outer usage of json_decode has already turned *all* the JSON text into a PHP object graph (of arrays and arrays in arrays and values within those arrays). – user2864740 Nov 22 '17 at 22:06
  • How should I approach the problem if I am using lists, or is this not possible? `data['age']` is not a string. – Tiskolin Nov 22 '17 at 22:07
  • Try this in the loop: `echo $key[0];` – user2864740 Nov 22 '17 at 22:08
  • What's your actual desired output here? I can't really tell what it is you're trying to achieve in the PHP step. – iainn Nov 22 '17 at 22:09
  • That gives me `oranges[null,null]`. Thanks, but is there some way to make the entire loop compatible with lists? – Tiskolin Nov 22 '17 at 22:10
  • My desired output is to transfer variables between Python and PHP and print out the values in PHP. – Tiskolin Nov 22 '17 at 22:11
  • You miss to check return values for errors early. Taking the snipped in the question as an example, `file_get_contents` can return `false` which means the file couldn't be opened. It is necessary to check each of the functions in use for their return codes and handle their error code. Another example is the `json_decode` in the loop. – hakre Nov 22 '17 at 22:11
  • Thank you. I've got a grip on the problem now. – Tiskolin Nov 22 '17 at 22:14
  • And to print out values, try `var_dump` first. You can fine-tune accessing certain values from the array / object returned by `json_decode` later on. – hakre Nov 22 '17 at 22:14

1 Answers1

1

The original code with issues:

<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a as $key) {
    // No need to use json_decode again
    // as it is already converted to an array
    // by the inital json decode statement
    array_push($arr,json_decode($key[0],true));
}
echo json_encode($arr);
?>

Pretty printed PHP Array which is stored inside $json_a:

Array
(
    [age] => 12
    [fruit] => Array
        (
            [0] => oranges
            [1] => apples
            [2] => peaches
        )

)

The problem:

In the original script, json_decode was used on an already decoded variable/array which returned nothing and hence null was appended to your list.

Code walkthrough: During the first iteration of the foreach loop,

$key will have the value 12 - which is a string

During the second iteration of the foreach loop,

$key will have the value - which is an Array

Array
(
    [0] => oranges
    [1] => apples
    [2] => peaches
)

The corrected code for printing all the fruits:

<?php
$string = file_get_contents("data.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a['fruit'] as $key) {
    array_push($arr,$key);
}
echo json_encode($arr);
?> 

The above snippet returns ["oranges","apples","peaches"]

RamC
  • 1,287
  • 1
  • 11
  • 15