I have this .json file:
{
"name": [
{
"text": "Привет мир!"
},
{
"text": "Hello World!"
}
]
}
. I want to read it, using nlohmann's json.cpp. There is my code:
#include <iostream>
#include <fstream>
#include "lib\include\nlohmann\json.hpp"
using namespace std;
using namespace nlohmann;
int main(){
setlocale(LC_ALL, "Russian"); //The console method does not work
json massive;
string tempp;
fstream f;
f.open("json1.json");
f >> massive;
f.close();
cout << massive["name"][0]["text"].dump()<<endl; //Russian text
cout << massive["name"][1]["text"].dump(); //English text
}
. When I start the program, it outputs the following information:
"Р?С?РёР?РчС' Р?РёС?!"
"Hello World!"
English language works good, but Unknown characters appear instead of the text in Russian. The json file encoding is utf-8. How can I take information in Russian language from a json file
i tried "setlocale(LC_ALL, "Russian")" Using temporary string variable can't solve problem
Solution to the problem:
Add to includes #include <locale>
and locale::global(std::locale{ ".UTF-8" }); cout.imbue(std::locale("ru_RU.UTF-8"));
to int main()
Assuming you are using Windows and MSVC (you've used wrong slash in include directive) this should work:
....
#include <locale>
int main() {
std::locale::global(std::locale{".UTF-8"}); // inform standard library application logic uses UTF-8
std::cout.imbue(std::locale("")); // use system locale to select output encoding
....
Will fail on other systems since ".UTF-8"
is not valid locale name on this platforms.
Also please make sure that your input file is UTF-8 encoded (JSon should use only this encoding).
Note that there is no locale name Russian
. On Windows valid locale name is for example: ru_RU.UTF-8
ru_RU.866
. For details see documentation.