2025-04-21【json】所有可存储格式举例

// JSON5 示例 - 包含所有 JSON 可存储的数据类型
{
  // 1. 字符串(必须双引号,但 JSON5 允许单引号)
  "string": "Hello World",
  'singleQuoteString': 'JSON5 允许单引号',
  
  // 2. 数字(整数/浮点数)
  "integer": 42,
  "float": 3.1415926,
  "scientificNotation": 1.23e+10,
  "hex": 0xFF, // JSON5 支持十六进制
  
  // 3. 布尔值
  "true": true,
  "false": false,
  
  // 4. null
  "nothing": null,
  
  // 5. 数组(可混合类型,JSON5 允许尾随逗号)
  "array": [
    "text",
    123,
    true,
    null,
    { "key": "value" }, // 数组内嵌套对象
  ], // ← 这个逗号在 JSON5 是合法的
  
  // 6. 对象(键可以不加引号,但推荐加)
  "object": {
    unquotedKey: "JSON5 允许键不加引号", // 仅 JSON5 支持
    "nested": {
      "deep": "value"
    }
  },
  
  // 7. 特殊值(JSON5 扩展支持)
  "infinity": Infinity,  // JSON5 支持
  "nan": NaN,            // JSON5 支持
  
  // 8. 日期(通常存储为字符串)
  "date": "2023-08-20T12:00:00Z", // ISO 8601 格式
  
  // 注释:JSON 标准不支持注释,这是 JSON5 的扩展特性
}

适应nlohmann::json库的读取,需要按照更严格的规则写json文件

具体如下:

  • 键必须用双引号括起来
  • 字符串值必须用双引号括起来
  • 最后一个键值对后面不能有逗号
  • 数组和对象中的元素也要遵循同样的逗号规则

1 在C++中,使用nlohmann::json创建并解析json字符串

#include <iostream>
#include <nlohmann/json.hpp>

// 为了方便使用,引入命名空间
using json = nlohmann::json;

int main() {
    // 创建 JSON 数组
    json roleProfilesArray = json::array();

    // 创建第一个对象
    json person1;
    person1["name"] = "Alice";
    person1["age"] = 25;
    person1["city"] = "New York";

    // 创建第二个对象
    json person2;
    person2["name"] = "Bob";
    person2["age"] = 30;
    person2["city"] = "Los Angeles";

    // 创建第三个对象
    json person3;
    person3["name"] = "Charlie";
    person3["age"] = 35;
    person3["city"] = "Chicago";

    // 将对象添加到数组中
    roleProfilesArray.push_back(person1);
    roleProfilesArray.push_back(person2);
    roleProfilesArray.push_back(person3);

    // 创建包含 roleProfiles 键的 JSON 对象
    json root;
    root["roleProfiles"] = roleProfilesArray;

    // 将 JSON 对象转换为字符串
    std::string jsonStr = root.dump(4);  // 缩进 4 个空格
    std::string jsonArrayStr = roleProfilesArray.dump(4);  // 缩进 4 个空格

    // 输出 JSON 字符串
    std::cout << "Created JSON string:" << std::endl;
    std::cout << jsonStr << std::endl;
    std::cout << "Created JSON array string:" << jsonArrayStr <<std::endl;

    // 从字符串中解析 JSON 数据
    json parsedJson = json::parse(jsonStr);
    json parsedJsonArray = json::parse(jsonArrayStr);
    // 读取并输出解析后的数据
    std::cout << "\nRead from JSON:" << std::endl;
    for (const auto& person : parsedJson["roleProfiles"]) {
        std::cout << "Name: " << person["name"] << ", Age: " << person["age"]
                  << ", City: " << person["city"] << std::endl;
    }

    // 输出解析后的 JSON 数组
    std::cout << "\nRead from JSON array:" << std::endl;
    for (const auto& person : parsedJsonArray) {
        std::cout << "Name: " << person["name"] << ", Age: " << person["age"]
                  << ", City: " << person["city"] << std::endl;
    }

    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容