json文件

Python3.8

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

一、概念

1.json官网

1.json官网:www.json.org
2.json的维基百科:https://en.wikipedia.org/wiki/JSON


2.json的概念

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人类阅读和编写,同时也易于机器解析和生成。JSON 主要用于服务器与客户端之间的数据交换,尤其在 Web 开发中应用广泛。

JSON 由 JavaScript 的对象表示法(object notation)演变而来,但由于其简洁性和可移植性,它被广泛应用于多种编程语言中。JSON 是完全语言独立的,但是它使用了 JavaScript 的语法,因此非常易于理解和使用。


3.序列化方案:xml、json

JSON比XML更轻量级。
在这里插入图片描述

在这里插入图片描述



二、json的数据类型

json既可以是object (键值对的集合),也可以是array (值的有序集合)。
json支持嵌套结构。


1.json的键:必须是带双引号的字符串

键(Key)要求
必须是字符串:在 JSON 中,所有的键(key)必须是字符串,并且必须用双引号 " 包裹。JSON 不允许使用数字、布尔值、null 或其他类型作为键。

有效的键:“name”, “age”, “address”
无效的键:name, age, 123(这些没有双引号,不能作为 JSON 键)
区分大小写:JSON 键是区分大小写的,这意味着 “name” 和 “Name” 被视为不同的键。

不能包含某些特殊字符:键名虽然是字符串,但通常建议避免包含特殊字符,如空格、逗号、冒号等,因为这可能导致解析错误。通常,JSON 键的字符集应限制为字母、数字、下划线 _、冒号等。


2.json的值:6种数据类型

json值的数据类型示例Python映射类型C++映射类型
对象 (object){“name” : “Edward”, “age” : 25}字典 dictnlohmann::json (嵌套对象)
数组 (array)[“apple”, “banana”]列表 liststd::vector<T>
字符串 (string)“Edward”strstd:string
数字 (number)25, 3.14int 或 floatint 或 double
布尔值 (boolen)true, falseTrue 或 Falsebool
空值 (null)nullNonenullptr

(1)对象 { }

对象(Object) { }

对象:由一对大括号 {} 包围,包含键值对
键和值之间用冒号: 分隔
键值对之间用逗号, 分隔。

例如:

{
    "name" : "Edward",
    "age"  : 25,
    "city" : "Shanghai",
    "hobbies" : ["running", "coding", "travelling", "reading"]
}

(2)数组 [ ]

数组 (Array) [ ]

数组:由一对方括号 [] 包围,包含多个值,值之间用逗号 , 分隔。例如:

["apple", "banana", "cherry"]
{
    "test_cases": [
      {
        "sequence_str": [
          "begin",
              "sip_90",
              "vms_window",
              "pcie_speed_switch",
          "end"
        ],
        "repeat": 3,
        "id": "fail_test"
      },
      {
        "sequence_str": [
          "begin",
              "pcie_3_7",
          "end"
        ],
        "repeat": 1,
        "id": "ppcie_test"
      }
    ]
  }



三、Python中的json

1.序列化:Python对象 转 json

json.dump() 和 json.dumps() 是序列化的操作( 将 Python 对象转为json字符串)

序列化(Serialization)是将 Python 对象转换为一种可以存储或传输的格式,例如 JSON 格式。

import json

data = {"name": "Alice", "age": 25}

# 使用 json.dump() 序列化为 JSON 并写入文件
with open('data.json', 'w') as file:
    json.dump(data, file)

# 使用 json.dumps() 序列化为 JSON 字符串
json_string = json.dumps(data)
print(json_string)  # 输出: {"name": "Alice", "age": 25}

2.反序列化:json 转 Python对象

json.load() 和 json.loads() 是反序列化的操作 (将 json 字符串转为 Python 对象)

json.load(file) 是 Python 标准库 json 模块中的一个方法,用于从文件中读取 JSON 数据并将其解析为 Python 对象


(1)读取json文件:load()

with open('data.json', 'r') as file:
    data = json.load(file)

举例:

import json

def print_json():
    with open('my_json.json' , 'r', encoding='utf-8') as file:
        data = json.load(file)   #使用 json.load()函数,读取json文件内容,并解析为Python对象
    print(data)                  #输出json中的所有数据

def print_json_particular():
    with open('my_json.json' , 'r', encoding='utf-8') as file:
        data = json.load(file)
    #访问json中的特定数据
    print(f"name : {data['name']}")
    print("city : {}".format(data['city']))

if __name__ == '__main__':
    #print_json()
    print_json_particular()
{
    "name" : "Edward",
    "age"  : 25,
    "city" : "Shanghai",
    "hobbies" : ["running", "coding", "travelling", "reading"]
}

(2)读取json字符串:loads()

json.load() 用于解析文件中的 JSON 数据。
json.loads() 用于解析字符串中的 JSON 数据

import json

json_string = '{"name": "Alice", "age": 25}'

data = json.loads(json_string)  # 解析 JSON 字符串

print(data)

(3)获取json中的键:get()

get()是Python中字典dict的函数,但是可以先用load()函数将json转化为字典,再用get()获取其键

注意,先import json



四、C++中的json

https://blog.csdn.net/Edward1027/article/details/141072003

1.nlohmann/json库

为了解析和处理 JSON 数据,C++ 需要借助第三方库,最常见的库是 nlohmann/json

C++ json库:
github搜json:nlohman/json
header-only形式:只用加头文件,不需要加链接选项

在这里插入图片描述


2.json对象

代码链接:https://github.com/WangEdward1027/workflow/blob/main/json/json.cpp

(1)json对象是object:下标填字符串
dump()是序列化

#include <iostream>
#include <string>
#include "nlohmann/json.hpp"
using std::cout;
using std::string;

//json对象是obejct: []中是字符串, 整体是{  }
void test1()
{
    nlohmann::json json_object;           //创建一个空的json对象
    json_object["key"] = "value";         //json对象是一个object
    string context = json_object.dump();  //dump() : 序列化
    cout << context << "\n";
}

//json对象是array: []中是数字, 整体是 [  ]
void test2()
{
    nlohmann::json json_object; 

    json_object[0] = "value";
    json_object[1] = 2204;
    json_object.push_back(1234); //json对象是array,则支持push_back()方法 
    
    //加入一个object {  }
    json_object[3]["key1"] = "value1";
    
    //加入一个array [  ]
    nlohmann::json child_object;
    child_object[0] = "000";
    child_object.push_back("111");
    child_object.push_back("222");
    child_object.push_back("333");
    json_object.push_back(child_object);

    cout << json_object.dump() << "\n";
}

//nlohmann::json::parse 解析字符串
void test3()
{
    char str[] = "[1,2,3,{\"key\":456}]";
    nlohmann::json json_object = nlohmann::json::parse(str);    
    cout << "json_object[0] = " << json_object[0] << "\n";
    cout << "json_object[1] = " << json_object[1] << "\n";
    cout << "json_object[2] = " << json_object[2] << "\n";
    cout << "json_object[3][\"key\"] = " << json_object[3]["key"] << "\n";
}

int main()
{
    test1();
    /* test2(); */
    /* test3(); */
    return 0;
}

3.json对象是array:下标填数字

数组可用push_back方法
在这里插入图片描述


4.序列化、反序列化

1.序列化:
dump()方法,将json对象序列化为string字符串

2.反序列化/解码/解析:
parse()方法,将string字符串解析为json对象。要求严格字符串符合json的格式。



五、json的注释

1.标准的 JSON 格式 不支持注释


2.使用键值对模拟注释:

{
  "_comment": "This is a comment",
  "name": "Alice",
  "age": 30
}

3.在代码中进行注释处理

另一种常见的做法是在代码中处理注释,而不是在 JSON 文件本身中放置注释。例如,在读取 JSON 文件后,使用脚本来忽略注释部分。
例如,你可以在加载 JSON 文件之前,将文件中的注释行(例如以 // 或 /* */ 开头的行)先删除掉:

import json

def load_json_with_comments(file_path):
    with open(file_path, 'r') as file:
        content = file.readlines()

    # 去掉注释行
    content = [line for line in content if not line.strip().startswith("//") and not line.strip().startswith("/*")]
    
    # 重新将内容拼接成字符串
    cleaned_content = "".join(content)
    
    # 解析 JSON
    return json.loads(cleaned_content)

# 加载带注释的 JSON 文件
data = load_json_with_comments("data_with_comments.json")
print(data)

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

11-01 4万+
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员爱德华

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值