I have a text file that has json on it. example below:
{'something' : 'ss'}
I am trying to read it on php and convert it to an array using json_decode.
$temp = '';
$fh = fopen( '/quiz' . $testid . '.txt' ,'r');
while ($line = fgets($fh)) {
$temp .= $line;
}
fclose($fh);
$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
But im getting null
If I don't json_decode it.. I can get the string.
I hope anyone can help me with this.
Thanks,
E
You don't need to do any parsing prior to calling json_decode
$contents = file_get_contents('/quiz' . $testid . '.txt');
$temp = json_decode($contents);
If you're still getting null, your JSON is likely invalid, you can use json_last_error to diagnose it.
This snippet works so i think that's a problem with your file parsing algorithm
<?php
$temp = '';
$temp='{
"a":1,
"b":[1,2,3]
}';
$temp = str_replace("\n","",$temp); //to remove new line
$temp = str_replace("\r","",$temp);
$temp = json_decode($temp);
var_dump($temp);
?>
As documented:
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.
The reason is that you don't have valid JSON.
Parse error on line 1:
{ 'something': 'ss'}
-----^
Expecting 'STRING', '}'
You probably mean:
{
"something": "ss"
}
Related
it seems to be a really easy question, but I am a little bit struggling: I am receiving a JSON String via JavaScript. Now I would like to iterate through the element. The resulting string has this form: {"title":value,"title2":value}
How can I iterate through this JSON string without knowing the key and value? I would like to get this output:
title -> value
title2 -> value2
I tried it this way:
$json = file_get_contents('php://input');
$array = json_decode($json,true);
$response = "Test";
foreach($array as $key=>$val) {
$response = $response. "$key : $val";
}
echo json_encode($response);
It only returns "Test". If I change it to echo json_encode($array), it returns the mentioned JSON String.
You mention javascript and php in your question, so I'm going to answer for both. Here is JS, two different ways. I believe that foreach is being deemphasized in favor of the (of) construct now, but I don't work primarily in JS:
var json = '{"title": 12, "title2": "text"}';
var data = JSON.parse(json);
Object.keys(data).forEach(function(key) {
console.log(key + ' -> ' + data[key])
})
for(key of Object.keys(data)) {
console.log(key + ' -> ' + data[key]);
}
And for PHP:
You can parse the json string into an array using json_decode:
$json = '{"title": 12, "title2": "text"}';
$arr = json_decode($json, true);
foreach($arr as $key=>$val) {
echo "$key : $val";
}
true parses it into an array instead of a std object.
https://www.php.net/manual/en/function.json-decode.php
Because of response's format you must decode the decoded format in order to take the object as you want
$json = '{"title": 12, "title2": "text"}';
$encoded=json_encode($json);
$decoded=json_decode($encoded);
$ddecode=json_decode($decoded);
foreach($ddecode as $key=>$val) {
echo "$key -> $val";
}
Output :
title -> 12 title2 -> text
I am stuck with this problem. Here is my code:
<?php
$arr = [
'from_name' => 'Rosresurs1.ru',
'from_email' => 'team#rosresurs.net',
'reply_email' => 'reply#rosresurs.net',
'subject' => 'Вас приветствует Росресурс!',
'reply_us' => 'Вопрос нам',
'charset' => 'UTF-8',
'headers' => ['List-Unsubscribe: <mailto:support#rosresurs.net?subject=Unsubscribe>, <http://rosresurs.net/escript/unsubscribe.php?token=$token>', 'Precedence: bulk']
];
echo 'Var dump array to encode: <br>';
var_dump($arr);
//Encoding
$done = json_encode($arr, JSON_UNESCAPED_UNICODE);
echo 'Echo encoded array to json: <br><br>';
echo $done . "<br><br><br><br>";
//Decoding
echo "Starting decoding from file: <br><br>";
$var = json_decode('mailconfig.json', 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 JSON error found: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL . '<br><br>';
echo 'Var dump variable: <br>';
var_dump($var);
And here is the output:
And here is JSON file, from which I tried to decode json:
{"from_name":"Rosresurs1.ru","from_email":"team#rosresurs.net","reply_email":"reply#rosresurs.net","subject":"Вас приветствует Росресурс!","reply_us":"Вопрос нам","charset":"UTF-8","headers":["List-Unsubscribe: , ","Precedence: bulk"]}
As you see my array contains UTF-8 symbols, so I have encoded them with JSON_UNESCAPED_UNICODE option. But when I try to decode(FROM FILE), it fails. But when I try to decode from encoded variable $done, it works perfectly.
My json file contains the same $done output(copied from the browser and pasted to file). json_last_error said it's a syntax error. But there is no one...
Also I pasted json string from file to online json syntax verify service and it returned "A valid JSON string".
P.S. I made a lot of echo helpers(see screenshot), so you can get into a problem fast(like starting encoding and decoding points).
According to the docs, json_decode() does not take a filename as a parameter, only a string.
If you want to decode JSON from a file you would need to do something like this:
$var = file_get_contents('mailconfig.json');
$var = json_decode($var);
Or, if you have to do this a lot, you could wrap the whole thing in a function:
function file_json_decode($path, $assoc = false){
if(file_exists($path)){
$json = file_get_contents($path);
$result = json_decode($json, $assoc);
} else {
$result = null;
}
return $result
}
And then call it like this:
$var = file_json_decode('mailconfig.json', true);
You are calling json_decode on a wrong parameter. The first parameter is the JSON data, not a filename! So if you want to parse the JSON from a file, you may write
json_decode(file_get_contents('mailconfig.json'), true);
I wrote this code:
$userAddresses = $database->getUsers("SELECT * FROM Users");
$address = array();
foreach($userAddresses as $user){
array_push($address, array("address"=> $user['address'],
"zipcode" => $user['zipcode']));
}
$locations = array(
"locations" => $address
);
$jsonLocations = json_encode($locations);
This code returns this json object:
{"locations":[
{"address":"Sneekermeer 25","zipcode":"2993 RL"},
{"address":"Boeier 13","zipcode":"2992 AK"}]}
I want to get the length of this array inside JavaScript. So I did this:
var address = '<?php echo $jsonLocations ?>';
After that I called console.log(address.length); to check the length but some how it counts all the chars (108 I think) in the address variable and returns that as length. address.locations.length also doesn't work.
Could someone help me out?
You can use JSON.parse()
var address = JSON.parse('<?php echo $jsonLocations ?>');
console.log(address.length); // will give you length;
Thats because the string needs to be decoded to an object. You can do this one of two ways.
Non recommended:
var address = <?= $jsonLocations ?>;
Or more correctly and safer:
var address = JSON.parse('<?= addslashes(json_encode($jsonLocations)) ?>');
Do not forget the call to addslashes to prevent any single quotes in your array from breaking the javascript string.
You can either remove the quotes around var address = '<?php echo $jsonLocations ?>'; (i.e var address = <?php echo $jsonLocations ?>;) or use JSON.parse to parse it as a string to an object.
I have tried the below and its working
var address = '{"locations":[{"address":"Sneekermeer 25","zipcode":"2993 RL"},{"address":"Boeier 13","zipcode":"2992 AK"}]}';
address = JSON.parse(address);
console.log(address.locations.length);
I have problems with treatment of Post. I received a string with the symbol '%' and two letters together, like 'Geci%de', but on PHP the var_dump I receive a different string, like 'Geci�', if try to use utf8_encode and utf8_decode, however the error continued, the strings resulted were 'GeciÞ' and'Geci?'. How is the better way to convert in the orignal string? I need to use in postgreSQL, it will be in select.
It is uses to treatment:
$data = strip_tags($data);
$data = trim($data);
$data = get_magic_quotes_gpc() == 0 ? addslashes($data) : $data;
$data = preg_replace("#(--|\|)#s", "", $data);
$data = urldecode($data); // especific to Ajax
return utf8_decode($data);
been trying to save my data from my while loop to script variables but no success. Did an example if how I want to save my php data to script variables. This doesn't work for me. Anyone have any idea? Don't want to save all data manually. Very greatful for answers! Ask if you don't understand :)
$id = 0;
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
echo "<script>";
echo "var data" . $id . " = " . $data . ";"; //???
echo "</script>";
}
The best thing to do here would almost certainly be to create an array (on the PHP side), and then output the entire array at once.
Assuming you've built an array in $array, here's how you would output it:
echo "<script>var data = " . json_encode($array) . ";</script>"
More on json_encode in the docs, but basically it encodes the PHP data as valid JSON. Since JSON is a subset of JavaScript object and array initializer syntax, you can safely output JSON text as the right-hand side of an assignment, as above.
In the client-side script, you'd access each item via data[0], data[1], etc. up through data[data.length - 1].
Separately, note what Nathan Loding pointed out in a comment on the question:
...[you're] calling mysql_fetch_array($data) and then [have] $data = $rows['data'] two lines further down, thus overwriting $data...
...which will tend to mess up your fetch loop.
You are duplicating the script tag on every iteration.
you also need to surround the data in double or single quotes.
But it is not so safe..
$id = 0;
$data = "";
$vars = "";
while($rows = mysql_fetch_array($data)){
$id = $id + 1;
$data = $rows['data'];
$vars .= "var data" . $id . " = \"" . addslashes( $data ). "\";"; //???
}
echo "<script>";
echo $vars;
echo "</script>";
}