Answer the question
In order to leave comments, you need to log in
How to decode json from unicode to js?
There is a json file on the server, I return data from it when requested, having previously passed it through the json_encode () function in PHP.
Further, from another server I make an ajax request to this URL and get the encoded json.
To use it, I have to run it twice through JSON.parse() .
In this regard, there are several questions.
1. In what form is it better to give json when implementing your API? (Encode or not?)
2. If you encode, is it possible to do without using JSON.parse() twice ?
json example:JSON.parse(JSON.parse(xhr.responseText))
"{\r\n\t\"country\": [\r\n\t\t\"\u0410\u0431\u0445\u0430\u0437\u0438\u044f\",\r\n\t\t\"\u0410\u0432\u0441\u0442\u0440\u0430\u043b\u0438\u044f\",
....
Answer the question
In order to leave comments, you need to log in
json file by passing it through the json_encode() function
If you want the Cyrillic alphabet to be immediately given in the correct form in the answer:
function response($data = [] {
header("Content-Type: application/json; charset=utf-8");
$flags = JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_PRETTY_PRINT;
$fails = implode('|', array_filter([
'\\\\',
$flags & JSON_HEX_TAG ? 'u003[CE]' : '',
$flags & JSON_HEX_AMP ? 'u0026' : '',
$flags & JSON_HEX_APOS ? 'u0027' : '',
$flags & JSON_HEX_QUOT ? 'u0022' : '',
]));
$pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
$callback = function ($m) {
return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
};
echo preg_replace_callback($pattern, $callback, json_encode($data, $flags));
exit;
}
попробуйте вместо PreparateSerializer использовать
from rest_framework.serializers import RelatedField
...
meds = RelatedField(source='med', read_only=True)
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question