json_decode(json_encode(an indexed array)) gives NULL - php

i encode the user entred testarea content with json_encode
here is how it storred in mysql (there is a return to line after "aaa")
{"content":"aaa
bbb"}
now when i get the the content from database and trying to decoded it using json_decode, i get NULL for this, instead of what expected.
what wrrong? a bug in PHP?
EDIT 1: more details
$data =array('content'=>$textareaText);
$addres_insert = "INSERT INTO `rtable` (`data`) VALUES ('".json_encode($data)."');";
$rows = mysql_query($addres_insert);
then to get the content
$query = "SELECT * FROM `rtable` WHERE id = '".$id."'";
$rows = mysql_query($query);
if ( $rows ){
$row = mysql_fetch_array($rows);
$res['data'] = json_decode($row['data']);//i tryed substr($row['data'],3) but didn't work
}

JavaScript and JSON do not allow line returns to be contained within a string. You need to escape them.
json_encode() should escape them automatically for you.
Here is the output of my playing with your JSON code supplied on the PHP interactive shell:
php > $json = '{"content":"aaa
php ' bbb"}';
php > var_dump(json_decode($json, true));
NULL
As you can see when I escape your line return it works just fine:
php > $json = '{"content":"aaa\n bbb"}';
php > var_dump(json_decode($json, true));
array(1) {
["content"]=>
string(8) "aaa
bbb"
}
This is also further discussed in a previous question relating to a similar problem: Problem when retrieving text in JSON format containing line breaks with jQuery

Related

PHP query (including PostGiS functions) returns nothing

I made a script to return IDs to me based on if a point is within a polygon. Currently this works when I invoke the script on my DB or on Postman, though when I invoke it else where it does not work.
I've looked into the post request body and 'Coordinates' is not a geography it is and encoded version (my guess), which I've tried to unpack within the query which hasn't worked. The only way I was able to unpack it within a different query was st_asgeojson and then use json_decode on the result but I want this to be done in one query.
Coordinates is passed as the following code:
"0101000020E6100000000000000040604000000000000039C0"
I want to convert this either outside the query or within it, to then get the results from my query. My PHP code is as follows:
<?php
require_once('../db.php');
$rawdata = file_get_contents("php://input");
$decoded = json_decode($rawdata, true);
$coordVar = handleCoords($decoded['event']['data']['new']['Coordinates']['coordinates']);
$res = pg_query_params($conn, 'SELECT "ShapeID" FROM "Shapes" WHERE st_within( ST_SetSRID( ST_MakePoint($1, $2), 4326), "Coordinates"::geometry) ', array($coordVar[0], $coordVar[1]));
while ($row = pg_fetch_assoc($res) ){
print_r($row['ShapeID]);
}
function handleCoords($data) {
return array($data[0], $data[1]);
}
?>
When testing my queries I obtained "Coordinates" from one of my tables which was a bytea code when looking at the results, as this is a geography data type. I got around this by using the ::geometry conversion, thinking about this, the issue I had was a simple fix. As the coordinates passed through the POST request body was also of the same data type, geography, therefore applying the same conversion would allow the query to work when invoked from any application.
The code is as follows:
<?php
require_once('../db.php');
$rawdata = file_get_contents("php://input");
$decoded = json_decode($rawdata, true);
$coordVar = handleCoords($decoded['event']['data']['new']['Coordinates']);
$res = pg_query_params($conn, 'SELECT "ShapeID" FROM "Shapes" WHERE st_within( ST_SetSRID( $1::geometry, 4326), "Coordinates"::geometry) ', array($coordVar));
while ($row = pg_fetch_assoc($res) ){
print_r($row['ShapeID]);
}
?>

Having trouble with json who have image url

I tried to make json file to convert my data from database to json and ended up with error (SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data)
when i use a database which not containt img_url it could work but when there is img_url always error.
i tried using .php extension and it works but the img_url is a mess but when i use .json extension it shows the error
this is my code:
$stmt = $conn->prepare("SELECT namajurusan, fakultas, deskripsi, img_url FROM tbl_prodi;");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($namajurusan, $fakultas, $deskripsi, $img_url);
$prodi = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['namajurusan'] = $namajurusan;
$temp['fakultas'] = $fakultas;
$temp['deskripsi'] = $deskripsi;
$temp['img_url'] = $img_url;
array_push($prodi, $temp);
}
//displaying the result in json format
echo json_encode($prodi);
Make sure you are not sending unparsed strings to your JSON before calling json_encode.
Try to see it using var_dump().
Encode the url using urlencode before adding it to the json.
PHP Docs: http://php.net/manual/en/function.urlencode.php
Update:
Instead of using array_push($prodi, $temp); use $prodi[] = $temp.

Special characters in column names

I got a database from a customer and need to create some logic around it, like reading and inserting entries.
When I tried some basic requests, like:
$json = array ();
$query = "select * from tab1";
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
die ( json_encode ( $json ) );
I surprisingly got an empty response.
Executing the same query directly from PHPMyAdmin, I got all expected results.
When I just dumped the JSON result in the browser, I noticed (extract):
... string(30) "ColumnName(�)" ...
It took me a while to find out, that there were columns name with some special charaters, like µ and °. Apparently, they could not be displayed properly so the whole response became invalid and I got no results.
Just removing those characters from the column name solved the problem.
Is there another solution, instead of just manually looking for those characters and removing them?
Because json_encode()/json_decode() deals only with UTF-8 encoding, you must convert all non utf8 encoded string to utf-8
You can use utf8-encode() function

Cannot Decode JSON API response

I have built an API for my shipping quote system. I feed it values and I get rate quotes back. It works fine but I cannot decode the JSON response. I get a NULL response and I'm not sure whats up. According to validaters the JSON is correct.
So what I essentially do is encode a PHP array on one side and I want to parse that on the other side using a browser and PHP. However, I get a NULL response.
Here is the JSON. Let me know if you need more.
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
I just want to decode this so I can parse it. If there is another way to parse please let me know.
Also, I searched SOF and the similar issues people were having here didn't help me.
This is the code I use to generate the JSON.
<?php
//include ('mysql_connect.php');
$result = mysql_query('select * from quote where user_id = "'.$user_id.'" order by netCharge asc limit 1');
if (!$result) {
die('Could not query:' . mysql_error());
}
if (!$result) echo mysql_error();
$api_data = array();
$api_count = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$api_data[carrier] = $row['carrier'];
$api_data[charge] = $row['netCharge'];
$api_data[service_days] = $row['serviceDays'];
$api_count++;
}
$api_data = json_encode($api_data);
print_r($api_data);
?>
This is what I'm using to grab that JSON data:
<?php
$input = file_get_contents('api_request.php?dest_zip=66101&weight=200&class=50&ltl_shipment=X&Residential_Delivery=X');
echo $input;
$obj = json_decode($input);
var_dump($obj);
?>
Have you tried the following
$array = json_decode($data, true);
Your response has an extra </div> in it.
Delete the div so that's valid JSON and the decode function will work.
http://trumrates.com/trumrates/rate/quote/signin/api_request.php?dest_zip=66101&weight=200&class=50&ltl_shipment=X&Residential_Delivery=X
Yields:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
</div>
Summary
The built-in function json_decode (see doc) should help. According to the official document, NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
I doubt the JSON string you read is actually NOT as same as PHP reads. Please make sure the string is NOT HTML escaped. And it is very important that keys and values in a JSON should be quoted by double quote. Single quote is malformed JSON, which might be considered as syntax error.
Example
To be a good demo, I put json string in file and then decode it using test.php.
In example.json:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
In test.php:
<?php
$input = file_get_contents('example.json');
echo $input;
// {"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
$obj = json_decode($input);
var_dump($obj);
// object(stdClass)#1 (3) {
// ["carrier"]=>
// string(12) "R&L Carriers"
// ["charge"]=>
// string(5) "99.13"
// ["service_days"]=>
// string(23) "Wednesday Oct. 22, 2014"
// }
When I wrote the code I used 'Enter' to give me spaces between lines of code. For some reason that translated to the JSON and that's why it wasn't working. I just deleted all the extra empty lines in my file and it worked.

MySQL > JSON, Causing errors with URL's

I have this code converting a mysql query to json:
$sth = mysql_query('SELECT * FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Works great, but i have in my database, a url field, here is a sample json row:
{"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"},
How can i get around this?
I suppose the "problem" is the presence of backslashed in the URLs ?
Like :
http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg
Well, that's not a problem for Javascript : try to assign your JSON data to a Javascript object, and display one of those URL :
var data = {"0":"4","id":"4","1":"Noter 2","name":"Noter 2","2":null,"desc":null,"3":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","iconurl":"http:\/\/images.apple.com\/webapps\/productivity\/images\/noter2_20091223182720-thumb.jpg","4":"1262032317","date":"1262032317","5":"dBelement, LLC","company":"dBelement, LLC","6":"http:\/\/dbelement.com\/","companyurl":"http:\/\/dbelement.com\/","7":"http:\/\/noter2.dbelement.com","appurl":"http:\/\/noter2.dbelement.com"};
alert(data[3]);
The URL is displayed correctly :
http://images.apple.com/webapps/productivity/images/noter2_20091223182720-thumb.jpg
So, the backslashes are not a "problem" ;-)
And, in fact, if you take a look at the "string" section of json.org, you'll see that slashes have to be backslashed for your string to be valid.
I don't see a problem here. If you're wondering why the URLs look like this:
http:\/\/www.example.com\/
Instead of like this:
http://www.example.com/
It's because the / characters are being appropriately escaped. When you unserialize the JSON object in javascript, the URLs will look as they do in your database.

Categories