Cannot Decode JSON API response - php

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.

Related

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]

Why is my PHP script not returning valid JSON

What's wrong with the JSON available at the link below???
http://bruceexpress.com/beerstore/test/getottawaeaststorebeerlist.php
Using PHP, I generated the above JSON from an SQL query and encoded it with json_encode.
$retval = mysqli_query($connection, $sql);
if(! $retval )
{
print('Could not select: ' . mysqli_error());
}
$storearray = array();
while($row = mysqli_fetch_assoc($retval))
{
$storearray[] = $row;
}
header('Content-Type: application/json');
echo json_encode($storearray);
In SWIFT:
json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
is throwing the NSCocoaErrorDomain Code=3840 exception. "JSON text did not start with array...."
I caught the exception and printed the data, and I am seeing this:
("<!DOCTYPE html>\n[{\"beer_id\":\"1650\",\"store_id\":\"4618\"},{\"beer_id\":\"1650\",\"store_id\":\"4607\"},{\"beer_id\":\"1650\",\"store_id\":\"4616\"},{\"beer_id\":\"1650\",\"store_id\":\"4604\"},{\"beer_id\":\"5213\",
.......... ( etc. I didn't copy the whole thing. Its too long.")
I know there are many questions like this, but I am still not seeing the answer I need. What is wrong my JSON???
At first encode your php file in UTF-8 without BOM. and delete all whitespaces before <?php tag
Secondly dont print anything before if you want to send header;
Thirdly you real need some check and return in your script, because i see now at least 2 bugs which will appear in a future

How To Pull JSON Data Using PHP

I'm trying to create a very simple php script that can pull data from a JSON file (array?) and echo it to the page. Sadly, I'm a complete newbie when it comes to PHP.
My goal is to dump all IP addresses and the corresponding client version into an output like this...
"127.0.0.1" "/Satoshi:0.9.1/"
"127.0.0.2" "/Satoshi:0.9.0/"
"127.0.0.3" "/Satoshi:0.9.0/"
"127.0.0.4" "/Satoshi:0.9.1/"
I can get the code to dump all data, but I'm not sure how to pull the ip and version without the ip and client version being named.. If that even makes sense?
Here is the code. What do I need to make it dump the correct data?
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$JSON = file_get_contents($url);
echo $JSON;
$data = json_decode($JSON);
var_dump($data);
?>
Thanks for your help!
Something like
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$data = (array)$data; // cast from stdClass to array, as results have int keys
foreach($data['nodes'] as $results){
echo $results[0]. " ". $results[3]."<br />";
}
?>
It doesn't makes much sense to convert an array of hashes into the one of some non-named entities. I guess that all you need is to dump it in the following way:
foreach($data as $t)
{
echo("ip=".$t->ip." ua=".$t->ua);
}
I don't think there is any reason to cast to an array. Just process the returned object. This one has the double quotes as requested as well.
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$json = file_get_contents($url);
$data = json_decode($json);
foreach($data->nodes as $results){
echo "\"".$results[0]."\" \"".$results[3]."\"<br />";
}
?>

json encode using php not able to get [] brackets

here is my code
<?
include '../dbConnect.php';
$amp=trim($_POST['amp']);
//$amp='AMP8';
//$sql=mysql_query("select tblRepairQueue.ackNo,tblRepairQueue.repairStatus,tblRepairQueue.savedAt from tblRepairQueue,AMPcustomers where AMPcustomers.phone1=tblRepairQueue.phoneNo and AMPcustomers.id='".$amp."'");
$sql=mysql_query("select phone1 from AMPcustomers where id='".$amp."'");
$response = array();
while($row=mysql_fetch_array($sql))
{
$sql_query=mysql_query("select ackNo,repairStatus,savedAt from tblRepairQueue where phoneNo='".$row['phone1']."'");
while($row1=mysql_fetch_array($sql_query)){
$ackNo=$row1['ackNo'];
$repairStatus=$row1['repairStatus'];
$savedAt=$row1['savedAt'];
$response[]=array('ackNo'=>$ackNo,'repairStatus'=>$repairStatus,'savedAt'=>$savedAt);
}}
print json_encode($response);
?>
output m getting as
{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
but i want the output to look like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]
Can anyone plz help in finding the mistake or what has to be done to get square brackets at the end
This is a bit strange because I have this code:
<?php
$array = array();
$array[] = array("ackNo"=>"26101211236759","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 00:55:25");
$array[] = array("ackNo"=>"26101211236780","repairStatus"=>"Closed and Complete","savedAt"=>"2012-10-26 10:55:25");
echo json_encode($array);
?>
And I get this correct form:
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"26101211236780","repairStatus":"Closed and Complete","savedAt":"2012-10-26 10:55:25"}]
This code should indeed output [{...},...]. So we can't really tell you what went wrong on your side. check the structure of the $response variable before the conversion to Json to see what went wrong.
Note that the code allows SQL injection. You must change it so that the parameters $amp and $row['phone1'] are escaped in the SQL queries. Even if you're relying on magic qoutes now, this solution is not future-proof (now-proof really) as support for this is was removed in PHP 5.4.
What you have written should work:
http://ideone.com/ErV9fr
// How many to add
$response_count=3;
// Your response, just templated
$response_template=array(
'response_number'=>0,
'ackNo'=>'dffdgd',
'repairStatus'=>'$repairStatus',
'savedAt'=>'$savedAt'
);
// Your empty response array
$response = array();
for($i=0;$i<$response_count;$i++) {
$response_template['response_number'] = $i; // Set the 'response number' to the itteration.
$response[]= $response_template; // Add the template to the collection
}
print json_encode($response);
Result:
[{"response_number":0,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":1,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"},{"response_number":2,"ackNo":"dffdgd","repairStatus":"$repairStatus","savedAt":"$savedAt"}]
In addition to this, you should sanitize your $amp variable. In it's current form it would be trivial for a user to escape your query and execute an arbitrary query against your DB.
http://www.php.net/manual/en/mysqli.real-escape-string.php
Please recheck it can not give you the output like that {"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25",{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}
as it is creating an array of array so it can not print like that.
It will always print like
[{"ackNo":"26101211236759","repairStatus":"Closed and Complete","savedAt":"2012-10-26 00:55:25"},{"ackNo":"031212102614381","repairStatus":"Closed and Complete","savedAt":"2012-12-02 23:05:54"}]

json_decode(json_encode(an indexed array)) gives NULL

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

Categories