json_decode returning an array of 1 - php

I am trying to decode some JSON into a php array. Here's the code excerpt:
$getfile="{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}";
$arr = json_decode($getfile, true);
$arr['day3'] = $selecter;
echo(print_r($arr));
The only thing that gets returned is '1'. I've checked JSONLint and it is valid json, so I'm wondering why json_decode is failing. I also tried checking what the array is before adding the day3 key to it, and I still return a '1'. Any help is appreciated!
Actual code:
$getfile = "";
$getfile = file_get_contents($file);
if ($getfile == "") {
writeLog("Error reading file.");
}
writeLog("getfile is " . $getfile);
writeLog("Decoding JSON data");
$arr = json_decode($getfile, true);
writeLog("Decoded raw: " . print_r($arr));
writeLog("Editing raw data. Adding data for day " . $day);
$arr['day3'] = $selecter;
writeLog(print_r($arr));
$newfile = json_enconde($arr);
writeLog($newfile);
if (file_put_contents($file, $newfile)) {
writeLog("Wrote file to " . $file);
echo $newfile;
} else {
writeLog("Error writting file");
}
These are the contents of $file (it's a text file)
{"fname":"Bob","lname":"Thomas","cascade":"bthomas","loc":"res","place":"home 2"}

We still don't know what's in your file. However if:
"{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}"
Then the extraneous outer double quotes will screw the JSON, and json_decode will return NULL. Use json_last_error() to find out. Might also be a UTF-8 BOM or something else ...
Anyway, the 1 is the result from print_r. print_r outputs directly, you don't need the echo. Also for debugging rather use var_dump()
More specifically you would want the print_r output returned (instead of the boolean success result 1) and then write that to the log.
So use:
writeLog(print_r($arr, TRUE));
Notice the TRUE parameter.

First, use a single quote. That will cause a parse error
$getfile= '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
I assume you have already declared $selecter and it has been assigned to some value.
Remove echo from echo(print_r($arr)) You don't need echo. print_r will also output. If you use echo, it will display 1 at the end of array.
The working code:
$getfile = '{"fname":"bob","lname":"thomas","cascade":"bthomas","loc":"res","place":"home 2"}';
$arr = json_decode($getfile, true);
$selecter = 'foobar';
$arr['day3'] = $selecter;
print_r($arr);
Hope this helps.

I had this problem when doing it like this:
if ($arr = json_decode($getfile, true)) {
$arr['day3'] = $selecter;
echo(print_r($arr));
}
Decoding it outside of if was the solution.

Related

PHP JSON_DECODE not working with special characters

I try to decode a json file and put it into an array but as soon as there is a special character the json_decode stops working:
$json_file_path = 'creds2.json';
$json_contents = file_get_contents($json_file_path);
$data = json_decode($json_contents, true);
var_dump($data);
returns NULL when creds2.json is:
{
"TEMP_REGEX": "[0-9]{2,3}[\.]{1}[0-9]{1}",
"HUMI_REGEX": "[0-9]{2,3}[\.]{1}[0-9]{1}"
}
but it returns the right value when it's:
{
"example": "examples",
"test123": "test123"
}
I already went around the forums but couldn't find a solution. Even ChatGPT couldn't help me out on this one.
I had to put another ‘\’. It is supposed to be “[\.]”.

PHP function to call JSON files

I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

cakephp log an array as var_dump

I need to jump into a server side code. It is used cakephp there. I would like to see a variable, I think it is a model, but I am not sure, let be a variable in or case.
CakeLog::write('debug', 'myArray'.var_export($myArray) );
it will have the output
myArray: Array
I would like to see similar output as var_dump can produce to the output.
Is that possible? if yes, than how?
Any help apreciated.
Just use print_r, it accepts a second argument not to output the result.
CakeLog::write('debug', 'myArray'.print_r($myArray, true) );
And if you don't want new lines, tabs or double spaces in your log files:
$log = print_r($myArray, true);
$log = str_replace(array("\n","\t"), " ", $log);
$log = preg_replace('/\s+/', ' ',$log);
CakeLog::write('debug', 'myArray' . $log);
Try:
CakeLog::write('debug', 'myArray'.print_r($myArray, true));
The true parameter makes print_r return the value rather than print on screen, so you can save it.
http://br2.php.net/manual/en/function.print-r.php
Somebody got a redirection method presented here.
This I have used to see what I have there, and it shows very clear.

PHP json_decode() returns NULL with seemingly valid JSON?

I have this JSON object stored on a plain text file:
{
"MySQL": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"DatabaseName": "(dbname)"
},
"Ftp": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"RootFolder": "(rf)"
},
"BasePath": "../../bin/",
"NotesAppPath": "notas",
"SearchAppPath": "buscar",
"BaseUrl": "http:\/\/montemaiztusitio.com.ar",
"InitialExtensions": [
"nem.mysqlhandler",
"nem.string",
"nem.colour",
"nem.filesystem",
"nem.rss",
"nem.date",
"nem.template",
"nem.media",
"nem.measuring",
"nem.weather",
"nem.currency"
],
"MediaPath": "media",
"MediaGalleriesTable": "journal_media_galleries",
"MediaTable": "journal_media",
"Journal": {
"AllowedAdFileFormats": [
"flv:1",
"jpg:2",
"gif:3",
"png:4",
"swf:5"
],
"AdColumnId": "3",
"RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
"FrontendLayout": "Flat",
"AdPath": "ad",
"SiteTitle": "Monte Maíz: Tu Sitio",
"GlobalSiteDescription": "Periódico local de Monte Maíz.",
"MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
"TemplatePath": "templates",
"WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
"WeatherMeasureType": "1",
"CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
"TimesSingular": "vez",
"TimesPlural": "veces"
}
}
When I try to decode it with json_decode(), it returns NULL. Why?
The file is readable (I tried echoing file_get_contents() and it worked ok).
I've tested JSON against http://jsonlint.com/ and it's perfectly valid.
What's wrong here?
This worked for me
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );
It could be the encoding of the special characters. You could ask json_last_error() to get definite information.
You could try with it.
json_decode(stripslashes($_POST['data']))
If you check the the request in chrome you will see that the JSON is text, so there has been blank code added to the JSON.
You can clear it by using
$k=preg_replace('/\s+/', '',$k);
Then you can use:
json_decode($k)
print_r will then show the array.
Maybe some hidden characters are messing with your json, try this:
$json = utf8_encode($yourString);
$data = json_decode($json);
I had the same problem and I solved it simply by replacing the quote character before decode.
$json = str_replace('"', '"', $json);
$object = json_decode($json);
My JSON value was generated by JSON.stringify function.
For me the php function stripslashes() works when receiving json from javascript. When receiving json from python, the second optional parameter to the json_decode call does the trick since the array is associative. Workes for me like a charm.
$json = stripslashes($json); //add this line if json from javascript
$edit = json_decode($json, true); //adding parameter true if json from python
this help you to understand what is the type of error
<?php
// A valid json string
$json[] = '{"Organization": "PHP Documentation Team"}';
// An invalid json string which will cause an syntax
// error, in this case we used ' instead of " for quotation
$json[] = "{'Organization': 'PHP Documentation Team'}";
foreach ($json as $string) {
echo 'Decoding: ' . $string;
json_decode($string);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
echo PHP_EOL;
}
?>
This error means that your JSON string is not valid JSON!
Enable throwing exceptions when an error happens and PHP will throw an exception with the reason for why it failed.
Use this:
$json = json_decode($string, null, 512, JSON_THROW_ON_ERROR);
Just thought I'd add this, as I ran into this issue today. If there is any string padding surrounding your JSON string, json_decode will return NULL.
If you're pulling the JSON from a source other than a PHP variable, it would be wise to "trim" it first:
$jsonData = trim($jsonData);
The most important thing to remember, when you get a NULL result from JSON data that is valid is to use the following command:
json_last_error_msg();
Ie.
var_dump(json_last_error_msg());
string(53) "Control character error, possibly incorrectly encoded"
You then fix that with:
$new_json = preg_replace('/[[:cntrl:]]/', '', $json);
Here is how I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding, mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode() to return null
In my case , i was facing the same issue , but it was caused by slashes inside the json string so using
json_decode(stripslashes($YourJsonString))
OR
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $YourJsonString), true );
If the above doesnt work, first replace the quotes from html quote , this might be happening if you are sending data from javascript to php
$YourJsonString = stripslashes($YourJsonString);
$YourJsonString = str_replace('"', '"', $YourJsonString);
$YourJsonString = str_replace('["', '[', $YourJsonString);
$YourJsonString = str_replace('"]', ']', $YourJsonString);
$YourJsonString = str_replace('"{', '{', $YourJsonString);
$YourJsonString = str_replace('}"', '}', $YourJsonString);
$YourJsonObject = json_decode($YourJsonString);
Will solve it,
It's probably BOM, as others have mentioned. You can try this:
// BOM (Byte Order Mark) issue, needs removing to decode
$bom = pack('H*','EFBBBF');
$response = preg_replace("/^$bom/", '', $response);
unset($tmp_bom);
$response = json_decode($response);
This is a known bug with some SDKs, such as Authorize.NET
If you are getting json from database, put
mysqli_set_charset($con, "utf8");
after defining connection link $con
Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
So, html_entity_decode() worked for me. Please try this.
$input = file_get_contents("php://input");
$input = html_entity_decode($input);
$event_json = json_decode($input,true);
It took me like an hour to figure it out, but trailing commas (which work in JavaScript) fail in PHP.
This is what fixed it for me:
str_replace([PHP_EOL, ",}"], ["", "}"], $JSON);
I recommend creating a .json file (ex: config.json).
Then paste all of your json object and format it. And thus you will be able to remove all of that things that is breaking your json-object, and get clean copy-paste json-object.
I also face the same issue...
I fix the following steps... 1) I print that variable in browser 2) Validate that variable data by freeformatter 3) copy/refer that data in further processing
after that, I didn't get any issue.
This happen because you use (') insted {") in your value or key.
Here is wrong format.
{'name':'ichsan'}
Thats will be return NULL if you decode them.
You should pass the json request like this.
{"name":"ichsan"}
I've solved this issue by printing the JSON, and then checking the page source (CTRL/CMD + U):
print_r(file_get_contents($url));
Turned out there was a trailing <pre> tag.
you should ensure these points
1. your json string dont have any unknowns characters
2. json string can view from online json viewer (you can search on google as online viewer or parser for json) it should view without any error
3. your string dont have html entities it should be plain text/string
for explanation of point 3
$html_product_sizes_json=htmlentities($html);
$ProductSizesArr = json_decode($html_product_sizes_json,true);
to (remove htmlentities() function )
$html_product_sizes_json=$html;
$ProductSizesArr = json_decode($html_product_sizes_json,true);
For my case, it's because of the single quote in JSON string.
JSON format only accepts double-quotes for keys and string values.
Example:
$jsonString = '{\'hello\': \'PHP\'}'; // valid value should be '{"hello": "PHP"}'
$json = json_decode($jsonString);
print $json; // null
I got this confused because of Javascript syntax. In Javascript, of course, we can do like this:
let json = {
hello: 'PHP' // no quote for key, single quote for string value
}
// OR:
json = {
'hello': 'PHP' // single quote for key and value
}
but later when convert those objects to JSON string:
JSON.stringify(json); // "{"hello":"PHP"}"
Before applying PHP related solutions, validate your JSON format. Maybe that is the problem. Try this online JSON format validator.
For me, I had to turn off the error_reporting, to get json_decode() working correctly. It sounds weird, but true in my case. Because there is some notice printed between the JSON string that I am trying to decode.
I had exactly the same problem
But it was fixed with this code
$zip = file_get_contents($file);
$zip = json_decode(stripslashes($zip), true);
I had the same issue and none of the answers helped me.
One of the variables in my JSON object had the value Andaman & Nicobar. I removed this & and my code worked perfectly.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>

Categories