2023年7月26日发(作者:)
pythonjson模块list转dict⾸先有⼀个.json⽂件,但我读取后显⽰的是list类型def readJsonText(path): with open(path,'r',encoding='utf-8') as f: textJson = nes() () #最初读取的类型 print(type(textJson)) #使⽤()函数后的类型 textJson = (textJson) print(type(textJson)) #使⽤()函数后的类型 textJson = (textJson) print(type(textJson)) #使⽤dict()函数后的类型 textJson = dict(textJson) print(type(textJson))可以看到:list -> str :yes
str ->list : yeslist -> dict :no (报错)如果我想将list->dict怎么办呢?def readJsonText(path): with open(path,'r',encoding='utf-8') as f: textJson = nes() () #最初读取的类型 print(type(textJson)) #使⽤()函数后的类型 textJson = (textJson[0]) print(type(textJson)) #使⽤dict()函数后的类型 textJson = dict(textJson) print(type(textJson))这样从list类型变成了dict类型,但是是怎么变的呢?原因:我们将list类型的textJson取了第0号位置,就变成了str类型,但这个str类型很特殊,是json类型,然后json类型就可以通过()函数转为dict类型了所以通过上⾯我们可以发现:如果⼀个json类型的⽂本是被 [ ] 给包裹上变成了list类型,那么我们可以去这个 [ ] 使它变成真正的json类型,然后就可以⽤()函数了list -> dict : nojson -> dict : yeslist -> str : yes
发布者:admin,转转请注明出处:http://www.yc00.com/news/1690307533a329876.html
评论列表(0条)