姊妹篇:【python】json转成成yaml
json数据
{
"name": "张三",
"age": 30,
"isMarried": false,
"children": [
{
"name": "小王",
"age": 5
},
{
"name": "小李",
"age": 3
}
],
"address": {
"street": "北京路123号",
"city": "北京市",
"postalCode": "100000"
},
"email": "zhangsan@example.com",
"phoneNumbers": [
{
"type": "home",
"number": "2341234"
},
{
"type": "office",
"number": "5678901"
}
],
"login": {
"username": "zhangsan",
"password": "password123"
},
"cart": [
{
"product": {
"name": "笔记本电脑",
"price": 1199.99,
"quantity": 2
}
},
{
"product": {
"name": "智能手机",
"price": 599.99,
"quantity": 1
}
}
]
}
code v1
# -- coding:utf-8 --
import json, yaml, os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def jsonToYaml(jsonPath, yamlPath):
with open(jsonPath, "r", encoding='utf-8') as f:
f_json = json.load(f)
with open(yamlPath, "w", encoding='utf-8') as f:
f_yaml = yaml.dump(f_json)
yaml.dump(yaml.safe_load(f_yaml), f, sort_keys=False)
if __name__ == '__main__':
jsonPath = "data.json"
yamlPath = "data.yaml"
jsonPath = os.path.join(BASE_DIR, jsonPath)
yamlPath = os.path.join(BASE_DIR, yamlPath)
jsonToYaml(jsonPath, yamlPath)
转化后:
转化后发现中文显示不是那么友善,全变成了:\u5317\u4EAC\u8DEF123\u53F7,这种形式;
主要原因:
在PyYAML中,默认的编码是UTF-8,但是如果你的字符串包含非UTF-8字符,比如中文,你可能需要指定一个不同的编码。在你的代码中,你可能需要指定在写入YAML文件时使用的编码是UTF-8,而不是默认的编码。
另外,当你使用 yaml.dump() 时,如果你想要保持中文等非ASCII字符的可读性,你应该使用 default_flow_style=False 参数,这样YAML文件将以块样式编写,而不是流动样式。
修改后的代码:
# -- coding:utf-8 --
import json, yaml, os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def jsonToYaml(jsonPath, yamlPath):
with open(jsonPath, "r", encoding='utf-8') as f:
f_json = json.load(f)
with open(yamlPath, "w", encoding='utf-8') as f:
f_yaml = yaml.dump(f_json)
# yaml.dump(yaml.safe_load(f_yaml), f, sort_keys=False)
# 使用safe_dump以避免潜在的安全风险,除非你完全信任源数据
yaml.safe_dump(f_json, f, default_flow_style=False, allow_unicode=True)
if __name__ == '__main__':
jsonPath = "data.json"
yamlPath = "data.yaml"
jsonPath = os.path.join(BASE_DIR, jsonPath)
yamlPath = os.path.join(BASE_DIR, yamlPath)
jsonToYaml(jsonPath, yamlPath)
转换后的结果:
address:
city: 北京市
postalCode: '100000'
street: 北京路123号
age: 30
cart:
- product:
name: 笔记本电脑
price: 1199.99
quantity: 2
- product:
name: 智能手机
price: 599.99
quantity: 1
children:
- age: 5
name: 小王
- age: 3
name: 小李
email: zhangsan@example.com
isMarried: false
login:
password: password123
username: zhangsan
name: 张三
phoneNumbers:
- number: '2341234'
type: home
- number: '5678901'
type: office
在本文中,我们探讨了技术性文章博客的重要性,它不仅能提升个人品牌,还能促进知识共享和技能成长。通过选择合适的平台、保持专业性和真诚性,并利用SEO和社交媒体策略来提高可见性,任何人都可以成功地撰写和推广技术性文章博客。记住,持续学习和实践是提升技术能力的的关键,而写作是这一旅程中的宝贵工具。让我们开始撰写影响未来的技术故事吧!