jpython 字典转字Json时常见问题
- 字典转json时,默认汉子变成ascii 字符码,而不是中文,如果你需要中文时需要添加参数【ensure_ascii=False】
import json city = { "cityCode": "110000", # "cityName": "北京"} print(json.dumps(city)) # >>> {"cityCode": "110000", "cityName": "\u5317\u4eac"} print(json.dumps(city, ensure_ascii=False)) # 禁用 ensure_ascii
#>>> {"cityCode": "110000", "cityName": "北京"}
- 字典转json时,默认会在冒号,逗号后面添加空格,如果去掉空格需要添加参数【separators=(',', ':')】
import json city = { "cityCode": "110000", # "cityName": "北京"} print(json.dumps(city, ensure_ascii=False)) # >>> {"cityCode": "110000", "cityName": "北京"} print(json.dumps(city, ensure_ascii=False, separators=(',', ':'))) # 去掉"," ,":"后面空格 # # >>> {"cityCode":"110000","cityName":"北京"}
- 字典转json时格式化输出,添加参数【indent=2】
import json city = { "cityCode": "110000", # "cityName": "北京"} print(json.dumps(city, ensure_ascii=False)) # >>> {"cityCode": "110000", "cityName": "北京"} print(json.dumps(city, ensure_ascii=False, indent=2)) # 格式后缩进2个字符,indent的值为非负整数; # # >>> { # "cityCode": "110000", # "cityName": "北京" # }
- 字典转json时按key进行排序,添加参数【sort_keys=True】
import json city = { "Name": "北京", # "Code": "110000", # } print(json.dumps(city, ensure_ascii=False)) # >>> {"Name": "北京", "Code": "110000"} print(json.dumps(city, ensure_ascii=False, sort_keys=True)) # 正向排序 #>>> {"Code": "110000", "Name": "北京"}