[json]定义、读写

发布时间:2023年12月18日

对象结构

对象结构是使用大括号“{}”括起来的,大括号内是由0个或多个用英文逗号分隔的“关键字:值”对(key:value)构成的。语法如下:

{ "键名1":1, "键名2":2, …… "键名n":值n };

其中,jsonObj指的是json对象。对象结构是以“{”开始,到“}”结束。其中“键名”和“值”之间用英文冒号构成对,两个“键名:值”之间用英文逗号分隔。这里的键名是字符串,但是值可以是数值、字符串、对象、数组或逻辑true和false12。

例如:

var jsonData = {
“name”: “Tom”,
“age”: 18,
“city”: “Shanghai”
};

数组结构

数组结构是用中括号“[]”括起来,中括号内部由0个或多个以英文逗号“,”分隔的值列表组成。语法如下:

[ { "键名1":1, "键名2":2 }, { "键名3":3, "键名4":4 }, …… ];

其中,arr指的是json数组。数组结构是以“[”开始,到“]”结束,这一点跟JSON对象不同。在JSON数组中,每一对“{}”相当于一个JSON对象,语法都非常类似12。

混合结构

{ "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}
import json

# 示例配置信息
config_data = { "programmers": [
{ "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
{ "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
}

# 将配置信息写入 JSON 文件
with open('config.json', 'w') as json_file:
	# indent:每个JSON对象前面都会有4个空格的缩进
    json.dump(config_data, json_file, indent=4)
# 打开JSON文件并读取内容
with open('config.json', 'r') as f:
    data = json.load(f)

# 访问配置信息
username = data['programmers'][0]['firstName']


print(username)

运行结果

Brett
文章来源:https://blog.csdn.net/qq_43496409/article/details/134957310
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。