Python 学习笔记 day 5 Json

Json创建并写入

import json

# 定义一个数据
data = {
    "name": "Miku",
    "age": 18,
    "city": "Tokyo",
    "languages": ["Chinese", "Japanese"]
}

# 将输入写入
with open('data.json', 'w') as file:
    json.dump(data, file, indent=4)

Json读取并使用

import json

# 将json写入到数据data
with open('data.json', 'r') as file:
    data = json.load(file)

# 将数据写入到变量
name = data.get('name')
age = data.get('age')
city = data.get('city')
languages = data.get('languages')

# 输出变量
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
print("Languages: ", languages[0]) #

Json转换为Python对象

import json

json_string = '{"name": "Miku", "age": 18, "city": "Tokyo"}'
data = json.loads(json_string)

print(data['name'])  # 输出: Miku

Json嵌套数据

import json

json_string = '''
{
    "name": "Miku",
    "address": {
        "street": "114514",
        "city": "Tokyo"
    },
    "phone_numbers": ["123-456-7890", "987-654-3210"]
}
'''
data = json.loads(json_string)

print(data['address']['city'])  # 输出: Tokyo
print(data['phone_numbers'][0])  # 输出: 123-456-7890

Json处理大文件

import json

data = [{"item": i} for i in range(1000)]

with open('output.json', 'w') as file:
    for item in data:
        file.write(json.dumps(item) + '\n')

with open('large_file.json', 'r') as file:
    for line in file:
        data = json.loads(line)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇