- 基本
# 1. 【python字典】转json格式【str】
import json
dic = {\'a\': 1, \'b\': 2, \'c\': 3}
str1 = json.dumps(dic, sort_keys=True, indent=4, separators=(\',\', \':\')) # 有换行缩进的str
str2 = json.dumps(dic)
\'\'\'
我们来对这几个参数进行下解释:
sort_keys:是否按照字典排序(a-z)输出,True代表是,False代表否。
indent=4:设置缩进格数,一般由于Linux的习惯,这里会设置为4。
separators:设置分隔符,在dic = {\'a\': 1, \'b\': 2, \'c\': 3}这行代码里可以看到冒号和逗号后面都带了个空格,这也是因为Python的默认格式也是如此,
如果不想后面带有空格输出,那就可以设置成separators=(\',\', \':\'),如果想保持原样,可以写成separators=(\', \', \': \')。
\'\'\'
# 2. 类似json格式【str】转python【dict】 使用demjson
pip install demjson
import demjson
js_json = "{x:1, y:2, z:3}"
py_json1 = "{\'x\':1, \'y\':2, \'z\':3}"
py_json2 = \'{"x":1, "y":2, "z":3}\'
data = demjson.decode(js_json) # {\'y\': 2, \'x\': 1, \'z\': 3}
# 3. json格式【str】转python【dict】
import json
str = \'{"accessToken": "521de21161b23988173e6f7f48f9ee96e28", "User-Agent": "Apache-HttpClient/4.5.2 (Java/1.8.0_131)"}\'
j = json.loads(str) # dict 类型
# 4. list格式的【str】转python【dict】
test_str = "[{\'PTP sync time between RU and DU: \': 2}, {\'Radio data path sync time: \': 2}, {\'Tx Carrier setup time in radio: \': 7}, "
str_list = [x.strip() for x in test_str.strip(\'[]\').split(\',\') if x.strip() is not \'\']
dic_list = [eval(x.strip()) for x in test_str.strip(\'[]\').split(\',\') if x.strip() is not \'\'] # eval把str转换成dic
# 5. 函数化【list】转json格式【str】
def list_to_json(str):
dic = {}
for i, j in enumerate(str):
dic[i] = j
return json.dumps(dic, sort_keys=True, indent=4, separators=(\',\', \': \'))
print(list_to_json([\'aa\',\'bb\',\'cc\']))
\'\'\'
{
"0": "aa",
"1": "bb",
"2": "cc"
}
\'\'\'
- json文件中做注释的文件load
def load_json(path):
import json
lines = [] # 第一步:定义一个列表, 打开文件
with open(path) as f:
for row in f.readlines(): # 第二步:读取文件内容
if row.strip().startswith("//"): # 第三步:对每一行进行过滤
continue
lines.append(row) # 第四步:将过滤后的行添加到列表中.
return json.loads("\n".join(lines)) #将列表中的每个字符串用某一个符号拼接为一整个字符串,用json.loads()函数加载
- json.load和json.loads区别
with open("文件名") as f:
print(type(f)) # <class \'_io.TextIOWrapper\'> 也就是文本IO类型
result=json.load(f)
with open("文件名") as f:
line=f.readline():
print(type(line)) # <class \'str\'>
result=json.loads(line)