How to JSON encode an array with French accents? - php

There are many threads about this but none of them helped me solve this problem.
$array=array(
"dépendre"=>"to depend",
"dire"=>"to say",
"distraire"=>"distracted",
"être"=>"to be (being)",
);
Gets encoded like this with json_encode :
"d\u00e9pendre":"to depend","dire":"to say","distraire":"distracted","\u00eatre":"to be (being)"
So far I have tried this:
array_walk_recursive($array,function($value,$key) {
$key = urlencode(utf8_decode($key));
});

Try this,
json_encode($array, JSON_UNESCAPED_UNICODE);
You should get this result;
{
"dépendre":"to depend",
"dire":"to say",
"distraire":"distracted",
"être":"to be (being)"
}

Please check the result from the following code:
<?php
$x=array(
"dépendre"=>"to depend",
"dire"=>"to say",
"distraire"=>"distracted",
"être"=>"to be (being)",
);
$encoded = json_encode($x);
var_dump($x);
var_dump(json_decode($encoded, true));
The string you get in your question is a correctly escaped JSON and could be successfully decoded.

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 “[\.]”.

How to remove backslashes from json response in php

I am getting json response as mentioned below:
"{\"id\":\"order_DPUVoS2YVnBccy\",\"entity\":\"order\",\"amount\":100,\"amount_paid\":0,\"amount_due\":100,\"currency\":\"INR\",\"receipt\":\"7550\",\"offer_id\":null,\"status\":\"created\",\"attempts\":0,\"notes\":[],\"created_at\":1570082483}"
I want output to be as:
{"id":"order_DPUVoS2YVnBccy","entity":"order","amount":100,"amount_paid":0,"amount_due":100,"currency":"INR","receipt":"7550","offer_id":null,"status":"created","attempts":0,"notes":[],"created_at":1570082483}
I tried using stripslashes() to remove backslashes, but its not working.
What do you mean by "not working"?
<?php
$unescapedJson = '{\"id\":\"order_DPUVoS2YVnBccy\",\"entity\":\"order\",\"amount\":100,\"amount_paid\":0,\"amount_due\":100,\"currency\":\"INR\",\"receipt\":\"7550\",\"offer_id\":null,\"status\":\"created\",\"attempts\":0,\"notes\":[],\"created_at\":1570082483}';
echo stripslashes($unescapedJson);
Output for PHP 7.1.25 - 7.4.0rc2:
{"id":"order_DPUVoS2YVnBccy","entity":"order","amount":100,"amount_paid":0,"amount_due":100,"currency":"INR","receipt":"7550","offer_id":null,"status":"created","attempts":0,"notes":[],"created_at":1570082483}
you have to do it when json decode:
$data = json_encode('yourjsonvariable'), true, JSON_UNESCAPED_SLASHES);

Print json in pretty format using php code

I have array like below.
$resultArr = array();
$resultArr['status code'] = 200;
$resultArr['result'] = "Success";
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
return $json;
This is giving result like below
"{\n \"status code\": \"200\",\n \"result\": \"Success\",\n}"
without Pretty_print the result is like below
"{\"status code\":\"200\",\"result\":\"Success\"}"
I want response to be like this
{
"status code": 200,
"result": "Success"
}
Is something like this can be done pls, I am using PHP, Running the request in postman and the response are mentioned above
Note: I need to avoid using echo, because we are using code sniffers in project, so echo is not recommended.
You used JSON_PRETTY_PRINT for beautify output purpose,
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
If you want to use it as response remove that parameter,
$json = json_encode($resultArr);
Above line should work.
First of all, remove the JSON_PRETTY_PRINT flag.
Secondly, your problem is with the backslashes (\). These are escape characters. I don't know how you are printing your json or how you are viewing it.
If I do:
echo $json;
It outputs:
{"status code":200,"result":"Success"}
The backslashes are probably added because you're doing an AJAX request. In order to solve this, you could use jQueries .parseJSON() or add dataType: "json" to your ajax request.
And if you really don't want the backslashes to be added:
$json = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
Update
It might help to output using the following header:
header('Content-Type: application/json');
1. for Output Of API You Can Use Api:
header('Content-Type: application/json');
2. Using JSON_PRETTY_PRINT
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
3. You want To Display In Chrome
https://addons.mozilla.org/en-US/firefox/addon/json-handle/?src=recommended

JSON not decoding in php

i am using json decoding function in php to decode this
{"department_id":"3123a79d-9e33-543f-c9be-4cc7ff79982c",
"ug_id":"217a783c-7970-8d92-6c99-5225a3ec533a",
"pg_id":"90da4eb5-6b75-44b0-2ce0-5226c8f60f8e",
"staff_id":"1e6364a3-0b3d-6384-a6c2-5225bd41c7fd",
"from_date":"date_start",
"to_date":"date_end"}
I have use json_decode($str) and json_decode($str,true) both, but i am getting null output. Please help me if possible.
Here is my complete code
$query='SELECT params FROM userreports WHERE id=\''.$_REQUEST['record'].'\'';
$query_exe=$db->query($query);
$res=$db->fetchByAssoc($query_exe);
$json=$res['params'];
$arr=json_decode($json,true);
echo '<pre>';
print_r($arr) ;exit;
Try following code it is working fine:
<?php
$str = '{"department_id":"3123a79d-9e33-543f-c9be-4cc7ff79982c",
"ug_id":"217a783c-7970-8d92-6c99-5225a3ec533a",
"pg_id":"90da4eb5-6b75-44b0-2ce0-5226c8f60f8e",
"staff_id":"1e6364a3-0b3d-6384-a6c2-5225bd41c7fd",
"from_date":"date_start",
"to_date":"date_end"}';
$arrStr = json_decode($str);
print_r($arrStr);
?>

PHP: How to json encode of hindi language in response

I am working with a translation API but here is an issue. I am using JSON in response and when I do json_encode of Hindi then the out is like "\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948"
My code is given below
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data); die;
and the response is
{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}
If you are running PHP 5.4 or greater, pass the JSON_UNESCAPED_UNICODEparameter when calling json_encode
Example:
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
This is correct json and when you display it in the browser and / or parse it, it will result in an object with the correct keys and values:
var json_string = '{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}',
json = JSON.parse(json_string);
// or directly:
var json2 = {"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"};
console.log(json_string);
console.log(json);
console.log(json2);
document.write(json_string);
document.write('<br>');
document.write(json.hindi);
document.write('<br>');
document.write(json2.hindi);
The reason for this is likely that these characters are not in UTF-8 (I could not find them, at least). From the PHP documentation on json_encode:
All string data must be UTF-8 encoded.
This means that it will have to convert it to a 'description' of the characters. Do not worry, if you decode it again it will very likely be correct.
I have a solution to this problem. It works fine for me.
$data = array();
$data['hindi'] = base64_encode('यह कार है');
$data['english'] = 'This is car';
$encoded_text=json_encode($data);
To retrieve the hindi part of data:
$hindi=base64_decode(json_decode($encoded_text)->hindi);

Categories