Can't decode JSON from file in PHP - php

I'm having troubles with json_decode in PHP:
I have this on file:
{1: ['oi','oi'], 2: ['foo','bar']}
And this is my php code:
<?php
$string = file_get_contents("quizen.json"); // the file
$json = json_decode($string);
echo $json[1][0]
?>
But the echo returns anything, I used var_dump, and I get NULL!
What's the problem?

The issue is that your file is not valid JSON since it uses single quotes for strings and has integers as object keys:
{1: ['oi','oi'], 2: ['foo','bar']}
Also, since the JSON is an object, you should decode it to an associative array using json_decode($string, true).
According to the JSON spec:
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array.
Also, the object keys need to be strings.
If you change the single quotes to double quotes and edit your PHP's decode_json call to decode to an associative array, it should work. For example:
JSON:
{"1": ["oi","oi"], "2": ["foo","bar"]}
PHP:
<?php
$string = file_get_contents("quizen.json"); // the file
$json = json_decode($string, true); // set to true for associative array
echo $json["1"][0];
?>

Related

Array turn to json using php

need your help on this one...
I'm trying to create a code that will get a .txt file and convert all text content to json.
here's my sample code:
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
I already got the result when i tried to echo the $json_contents
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]
but when I tried to echo using like this method $json_contents[0]
I only got per character result.
Code
Result
hope you can help me on this one..
thank you
As PHP.net says
"Returns a string containing the JSON representation of the supplied value."
As you are using $json_contents[0] this will return the first char of the json string.
You can do this
$conents_arr[0]
Or convert your json string to PHP array using
$json_array = json_decode($json_contents, true);
echo $json_array[0];
It is happening because $json_contents is a string. It might be json string but it's string so string properties will apply here and hence when you echo $json_contents[0] it gives you first character of the string. You can either decode the encoded json string to object like below:
$json = json_decode($json_contents);
echo $json[0];
or echo it before the json_encode:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
json_encode() function takes an array as input and convert it to json string.
echo $json_contents; just print out the string.
if you want to access it you have to decode the JSON string to array.
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];

Can I decode JSON containing PHP code?

Is it possible to have a JSON string containing PHP Code, and to have this string decoded?
For example, this works as it should:
$array = ["page", "is-home", $_SERVER["REQUEST_URI"] == "/"];
var_export($array);
// array (
// 0 => 'page',
// 1 => 'is-home',
// 2 => false,
// )
This, does not work:
$json = '["page", "is-home", $_SERVER["REQUEST_URI"] == "/"]';
$array = json_decode($json); // returns NULL
echo json_last_error_msg(); // Syntax error
The second example will only work if $_SERVER["REQUEST_URI"] == "/" is removed from the json string.
Is there a way to parse this string using json_decode, and if not, are there alternative methods to accomplish this?
Many thanks!
UPDATE
The $_SERVER["REQUEST_URI"] == "/" has to be parsed. I am trying to extend Blade Templating so that I can implement parsed functions such as this:
#add-request('page', 'is-home', $_SERVER["REQUEST_URI"] == '/')
UPDATE #2
To try to simplify the matter, I need to turn a string into an object.
$str = '["page", "is-home", $_SERVER["REQUEST_URI"] == "/"]'; // this is obtained by parsing the top blade extension (not important how)
From the string I need the following array:
$array = ["page", "is-home", true / false ]
Keep in mind that the original string can contain theoretically any PHP object for one of the JSON values.
I think you're on the right track, but instead of trying to "simulate" a decode by putting single-quotes, why not (for your proof of concept) first ENCODE, then 'echo' / 'print' the value that it returns, and then DECODE to see what it returns.
Why don't you use json_encode() to obtain json string??
// create json string by json_encode() from array
$json = json_encode([
"page",
"is-home",
$_SERVER["REQUEST_URI"] == "/"
]);
// decode the encoded string with no error, of course ....
$array = json_decode($json);
As you can clearly see in the output, your first array does not contain any PHP at all.
$array = ["page", "is-home", $_SERVER["REQUEST_URI"] == "/"];
automatically fills $array[2] with the boolean false, not with PHP code.
So, let's assume you can't do such a calculation on the client (in fact, you can do this calculation in javascript as well). So you would have to send it to the server as a json string (properly encoded), decode it, eval it, and post the result back into the array.
$json = '["page", "is-home", "$_SERVER[\"REQUEST_URI\"] == \"/\""]';
$array = json_decode($json);
$array[2]=eval($array[2]);
But please don't do this! It is a big security hole.
Instead, feel free to ask a new question as to how you can do this calculation in javascript as well.
For your case you could do:
$is_home = $_SERVER["REQUEST_URI"] == "/";
$json = '["page", "is-home", '. $is_home .']';
$array = json_decode($json);
That's because you are using a variable in your string which is not parsed. In addition, $_SERVER["REQUEST_URI"] == "/" returns false. Boolean false will be converted to an empty string if it is concatenated to a string.
You should rewrite your code to something like this:
// Is the request URI equal to "/"?
$reqUriTest = ($_SERVER["REQUEST_URI"] == "/");
// If boolean false is converted to a string, it will become an empty string.
// So we need to explicitly use values "true" or "false".
$reqUriStr = ($reqUriTest ? "true" : "false");
// Now we can insert $reqUriStr into the JSON string.
$json = '["page", "is-home", '.$reqUriStr.']';
$array = json_decode($json);

How can I parse json array string to array on php

How can I parse json array string to array on php
'[{"a": "1", "b": "2"}, {"a": "3"}]'
seems json_decode allows parse only objects but not arrays. Should it be manually parsed to array before using json_decode?
Seems problem in string. I get a variable with json, and if I output it, looks like the json is valid
echo($jsonvar); //result [{"title":"Home","id":"/","url":"/"}]
but when I try parse string from the variable, the result is nothing even when string is trimmed
echo('[{"title":"Home","id":"/","url":"/"}]', true); //nice parsed array
echo($jsonvar, true); //nothing
echo(trim($jsonvar, " \t\n\r\0\x0B"), true); //nothing
Pass the true as a second parameter to your json_decode() to parse the json string to array.
$json='[{"a": "1", "b": "2"}, {"a": "3"}]';
$arr= json_decode($json,true);
print_r($arr);
You can get the json into array by using the true flag in json_decode()
<?php
$str = '[{"a": "1", "b": "2"}, {"a": "3"}]';
$arr=json_decode($str,true);
print_r($arr);

Convert JSON String to Array

I have this JSON string
{"ticker":{"high":736.45099,"low":681,"avg":708.725495,"vol":13038780.63684,"vol_cur":18382.55965,"last":726,"buy":726,"sell":724.5,"updated":1388242741,"server_time":1388242743}}
How can i get the "last" parameter after doing json_decode()?
Do like this
<?php
$json='{"ticker":{"high":736.45099,"low":681,"avg":708.725495,"vol":13038780.63684,"vol_cur":18382.55965,"last":726,"buy":726,"sell":724.5,"updated":1388242741,"server_time":1388242743}}';
$json_arr=json_decode($json,true);
echo $json_arr['ticker']['server_time'];//"prints" 1388242743 which is the last param "server time"
Use json_decode with parameters json string and TRUE.When TRUE, returned objects will be converted into associative arrays.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));
?>
http://php.net/json_decode

counting the number of arrays in a php decoded string

I have two json decoded strings:
{"Coords":[{"Accuracy":"66","Latitude":"88","Longitude":"99","Timestamp":"100"}]}
and I have another string
{"Coords":[{"Accuracy":"222","Latitude":"333","Longitude":"444","Timestamp":"2013"},{"Accuracy":"3434","Latitude":"565","Longitude":"676","Timestamp":"7878"}]}.
Is there a way to be able to echo that the first string has 1 array and the second string has 2? My method was as following:
$Json_String=($_POST['Json']); $Json_Decoded= json_decode($Json_String, true); echo count(json_decode($Json_String, true));
where $Json_String is just what I'm pasting into a text field for now for testing purposes.
Do,
json_decode($jsonString, true);
for each string that will return you array. You can then count the length of array easily.
if you just want to kown the length try this:
echo substr_count (' {"Coords":[{"Accuracy":"222","Latitude":"333","Longitude":"444","Timestamp":"2013"},{"Accuracy":"3434","Latitude":"565","Longitude":"676","Timestamp":"7878"}]}.','Accuracy');

Categories