python(6)——處理json

來源:互聯網
上載者:User

標籤:imp   www.   轉換   nbsp   asc   als   load()   microsoft   class   

  • json是通用的資料類型,所有語言都認識 (介面的傳回值一般都是json字串)
  • k-v {} json中的key value必須用雙引號包起來 校正json格式是否正確 www.bjson.com
  • json是字串

json串轉成字典:json.loads()

 1 import json 2 s=‘‘‘ 3 { 4         "error_code": 0, 5         "stu_info": [ 6                 { 7                         "id": 309, 8                         "name": "小白", 9                         "sex": "男",10                         "age": 28,11                         "addr": "河南省濟源市北海大道32號",12                         "grade": "天蠍座",13                         "phone": "18512572946",14                         "gold": 10015                 },16                 {17                         "id": 310,18                         "name": "小白",19                         "sex": "男",20                         "age": 28,21                         "addr": "河南省濟源市北海大道32號",22                         "grade": "天蠍座",23                         "phone": "18516572946",24                         "gold": 10025                 }26         ]27 }28 ‘‘‘29 res=json.loads(s)  # 將json串轉換成字典30 print(res)31 print(type(res))32 print(res.keys()) 

result:

1 {‘stu_info‘: [{‘sex‘: ‘男‘, ‘phone‘: ‘18512572946‘, ‘id‘: 309, ‘grade‘: ‘天蠍座‘, ‘name‘: ‘小白‘, ‘gold‘: 100, ‘age‘: 28, ‘addr‘: ‘河南省濟源市北海大道32號‘}, {‘sex‘: ‘男‘, ‘phone‘: ‘18516572946‘, ‘id‘: 310, ‘grade‘: ‘天蠍座‘, ‘name‘: ‘小白‘, ‘gold‘: 100, ‘age‘: 28, ‘addr‘: ‘河南省濟源市北海大道32號‘}], ‘error_code‘: 0}2 <class ‘dict‘>3 dict_keys([‘stu_info‘, ‘error_code‘])

json.loads()和json.load()區別

1 f=open(‘stus.json‘,encoding=‘utf-8‘)2 user_dic=json.loads(f.read()) #傳入字串3 print(user_dic)4 5 f=open(‘stus.json‘,encoding=‘utf-8‘)6 user_dic=json.load(f)  #直接傳入檔案對象7 print(user_dic)

 

字典轉成json串:json.dumps()

 1 import json 2 stu={‘小小‘:‘123456‘,‘小黑‘:‘23456‘,"小臂":‘45655‘,‘ll‘:‘455756454‘} 3 res2=json.dumps(stu,indent=8,ensure_ascii=False)  #indent控制縮排  ensure_ascii 正常顯示中文 4 print(type(res2)) 5 print(res2) 6 with open(‘stus.json‘,‘w‘,encoding=‘utf-8‘) as f: 7  f.write(res2) 8  9 #dump()  如果要把字典寫入檔案中,用dump比dumps方便      dump()和load()都是和檔案相關的10  json.dump(stu, f, indent=4, ensure_ascii=False) #dump直接將字典寫到檔案中,不需要再寫一次write()

result:

<class ‘str‘>{        "ll": "455756454",        "小臂": "45655",        "小黑": "23456",        "小小": "123456"}

 

python(6)——處理json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.