Fork me on GitHub

【进阶05】【自学笔记】Python JSON序列化与反序列化

一、基本用法

JSON对数据进行封装。python和json数据类型的转换,看作为编码与解码。

1)编码json.dumps(A):(dict类型数据变成json字符串类型)

 

import json
d=dict(name="Bob",age=20,score=80)
print("python dist类型编码成json字符串类型")
en_json=json.dumps(d)
print(en_json)
print(type(en_json))
 
2)解码json.loads(B):       (json解码为python类型)
 
import json
en_json='{"name": "Bob", "age": 20, "score": 80}'
print(type(en_json))
print("json类型解码成python dict类型")
de_json=json.loads(en_json)
print(de_json)
print(type(de_json))

 

二、字典、列表、字符串 之间的转换

1)列表与字符串转换

列表内容拼接成字符串

l=['a','b','c']
res="".join(l)
print(res)

 返回结果:

abc

列表中的值转换成字符串

l=['a',1,'b','c',2]
res=[str(i) for i in l]
print(res)

2)字符串转换成列表 

 

l="['a',1,'b','c',2]"
print(eval(l))

返回结果:

['a', 1, 'b', 'c', 2]

  

将字符串每个字符转成列表中的值 

l="abc"
print(list(l))

返回结果:

['a', 'b', 'c']

  

将字符串按分割成列表

l="a b c"
print(l.split(" "))

返回结果:

['a', 'b', 'c']

  

3)列表与字典转换

l=["a","b","c"]
t=[1,2,3]
res=dict(zip(l,t))
print(res)

返回结果:

{'a': 1, 'b': 2, 'c': 3}

  

4)字典转列表

l={'a': 1, 'b': 2, 'c': 3}
t=list(l.keys())
print(t)
v=list(l.values())
print(v)

 返回结果:

['a', 'b', 'c']
[1, 2, 3]

  

 

  

 

 

  

posted @ 2022-01-01 23:58  橘子偏爱橙子  阅读(45)  评论(0编辑  收藏  举报