[C++]Json 学习笔记

Json 学习笔记

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于ECMAScript的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C、C++、C#、Java、JavaScript、Perl、Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(一般用于提升网络传输速率)。

本文大致介绍一个较为使用的json开源库。json开源库

常用方法

1.首先要引入json作用域。

using json = nlohmann::json;

json提供了cin,cout的输入输出流的操作符。但需要注意的是,cin要有ctr + D结束输入。cout会自动把json转换为string。

#include <iostream>
#include "json.hpp"
using json = nlohmann::json;
using std::cout;
using std::endl;
using std::cin;

int main(int argc, const char * argv[]) {
    json temp;
    cin >> temp;
    cout << temp << endl;
    return 0;
}
/*
输入:
{
  "pi": 3.141,
  "happy": true,
  "name": "Niels",
  "nothing": null,
  "answer": {
    "everything": 42
  },
  "list": [1, 0, 2],
  "object": {
    "currency": "USD",
    "value": 42.99
  }
}
{
  "answer":{
  "everything":42},"happy":true,"list":[1,0,2],"name":"Niels","nothing":null,"object":{
  "currency":"USD","value":42.99},"pi":3.141}
Program ended with exit code: 0
*/

2. 键值对

提供根据键直接生成键值对的方法。(类似于map,如果不存在该键的话,就生成一个这个键。)

#include <iostream>
#include "json.hpp"
using json = nlohmann::json;
using std::cout;
using std::endl;
using std::cin;

int main(int argc, const char * argv[]) {
    // create an empty structure (null)
    json j;

    // add a number that is stored as double (note the implicit conversion of j to an object)
    j["pi"] = 3.141;

    // add a Boolean that is stored as bool
    j["happy"] = true;

    // add a string that is stored as std::string
    j["name"] = "Niels";

    // add another null object by passing nullptr
    j["nothing"] = nullptr;

    // add an object inside the object
    j["answer"]["everything"] = 42;

    // add an array that is stored as std::vector (using an initializer list)
    j["list"] = { 1, 0, 2 };

    // add another object (using an initializer list of pairs)
    j["object"] = { {
  "currency", "USD"}, {
  "value", 42.99} };

    // instead, you could also write (which looks very similar to the JSON above)
    json j2 = {
        {
  "pi", 3.141},
        {
  "happy", true},
        {
  "name", "Niels"},
        {
  "nothing", nullptr},
        {
  "answer", {
            {
  "everything", 42}
        }},
        {
  "list", {
  1, 0, 2}},
        {
  "object", {
            {
  "currency", "USD"},
            {
  "value", 42.99}
        }}
    };
    cout << j << endl;
    cout << endl;
    cout << j2 << endl;
    return 0;
}
/*
{
  "answer":{
  "everything":
  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值