vscode格式化 json文件 快捷键
- 在Windows中,vscode格式化代码快捷键是“Shift+Alt+F”;
- 在Mac中,vscode格式化代码快捷键是“Shift+Option+F”;
- 在Ubuntu中,vscode格式化代码快捷键是“Ctrl+Shift+I”
测试例子
从文件读JSON
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
void test1();
int main()
{
test1();
}
void test1() {
std::ifstream f("Files/example.json");
json data = json::parse(f);
cout << data;
}
从json字符创建nlohmann::json对象
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
void test2();
int main(){
test2();
}
void test2() {
json ex1 = json::parse(R"(
{
"pi": 3.141,
"happy": true
}
)");
cout << ex1<<endl;
using namespace nlohmann::literals;
json ex2 = R"(
{
"pi": 3.141,
"happy": true
}
)"_json;
cout << ex2<<endl;
json ex3 = {
{"happy", true},
{"pi", 3.141},
};
cout << ex3 << endl;
}
使用nlohmann::json类
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
void test3() {
json j;
//数字
j["pi"] = 3.14;
//布尔型
j["happy"] = true;
//空指针
j["nothing"] = nullptr;
//字符串
j["name"] = "Linda";
//对象中创建对象
j["answer"]["number"] = 42;
//列表
j["list"] = { 1,0,2 };
//创建对象
j["object"] = { {"currency", "USD"}, {"value", 42.99} };
cout << j << endl;
std::ofstream outputfile("Files/test3.json");
outputfile << j;
}
int main()
{
test3();
}
输出test3.json
{
"answer": {
"number": 42
},
"happy": true,
"list": [
1,
0,
2
],
"name": "Linda",
"nothing": null,
"object": {
"currency": "USD",
"value": 42.99
},
"pi": 3.14
}
转换为std::string 类型
#include <iostream>
#include <fstream>
#include "json.hpp"
using json = nlohmann::json;
using namespace std;
void test4() {
json j = json::parse(R"(
{
"pi": 3.141,
"happy": true
}
)");
std::string s = j.dump();
//格式化输出
std::string s2 = j.dump(4);
cout << s << endl;
cout << s2 << endl;
}
int main()
{
test4();
}