nlohmann json 使用笔记

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();   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值