python3 之 格式化json

python3 之 格式化json
import json

json_string = None

with open(“json_file.json”) as f:
json_string = f.read()
try:
parsed_json = json.loads(json_string)
formatted_json = json.dumps(parsed_json, indent = 4,sort_keys=True)
with open(“json_file.json”,“w”) as f:
f.write(formatted_json)
except Exception as e:
print(repr(e))

Parameter indent decides the number of spaces to use for indentation.

Parameter sort_keys decides whether the keys in formatted JSON should be in sorted order or not. Default value is False.

Bonus: You can pretty-print the small JSON string directly at command terminal without using python script file. Use below line of code.

echo ‘{“first_name”: “Anurag”, “last_name”: “rana”}’ | python -m json.tool
示例:
[root@promote ~]# echo ‘{“first_name”: “Anurag”, “last_name”: “rana”}’ | python -m json.tool
{
“first_name”: “Anurag”,
“last_name”: “rana”
}

[root@promote ~]# echo ‘{“first_name”: “Anurag”, “last_name”: “rana”}’ | python -m json.tool
{
“first_name”: “Anurag”,
“last_name”: “rana”
}

root@promote ~]# echo ‘{“job”:“developer”,"name ":"lmx ","sex ":“male”}’ | python -m json.tool
{
“job”: “developer”,
"name ": "lmx ",
"sex ": “male”
}
[root@promote ~]# python -c “import paramiko”
[root@promote ~]# echo ‘{“first_name”: “Anurag”, “last_name”: “rana”}’ | python -m json.tool
{
“first_name”: “Anurag”,
“last_name”: “rana”
}

[root@promote CV]# echo ‘{ “address”:{ “province”:“zhejiang”," city":“hangzhou” }," name":“lmx”, " sex": “male” }’ | python -m json.tool
{
“address”: {
“province”: “zhejiang”,
" city": “hangzhou”
},
" name": “lmx”,
" sex": “male”
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值