PYTHON-Jsonモジュール

5339 ワード

Jsonモジュール
全称「JavaScript Object Notation」(JavaScriptオブジェクト表現)テキストベースで言語と独立した軽量レベルのデータ交換フォーマットです.読みやすい文字に基づいて、属性値またはシーケンス性の値からなるデータオブジェクト(キー値ペア)を転送するために使用されます.
Js公式サイトhttps://www.json.org/
構文規則
  • データは、キー値ペアからなる
  • である.
  • キー値ペアカンマで分離
  • 大かっこにオブジェクトを保存する
  • 中括弧に配列
  • を保存する
    現在,インターネット開発前後のデータ相互利用の基本はjsonである.
    方法
    pythonとjsのタイプの違い
    Python
    Json
    辞書dict
    オブジェクトclass
    リストリストまたはメタグループtuple
    はいれつ
    文字列str
    文字列
    整数intと浮動小数点float
    数値
    ブールTrueとFalse
    trueまたはfalse
    None
    null
    JsonAPI
    json.dumps(obj)
    pythonデータをjson形式のデータに変換
    json.loads(s)
    jsonデータをpython形式のデータに変換
    json.dump(obj,fp)
    pythonデータをjson形式のデータに変換してファイルに保存
    json.load(fp)
    ファイルからjsonデータを読み出しpython形式のデータに変換
    使用前にガイドパッケージが必要です
    import json
  • json.dumps(obj)pythonデータをjson形式のデータ
    dict1 = {'name':'yuxuan','age':15,'sex':' '}
    res1 = json.dumps(dict1)
    #res1 dict1   json      
    #indent     
    res1 = json.dumps(dict1,indent=2)
    #        ,  
    res1 = {
      "name":"yuxuan",
      "age":15,
      "sex":" "
    }
    #ensure_ascii      ensure_ascii=False        ASCII  
    #        
    res1 = json.dumps(dict1,indent=2,ensure_ascii=False)
    
  • に変換する
  • json.loads(s)jsonデータをpython形式のデータ
    #       json   res1   python    
    res2 = json.loads(res1)
    
  • に変換する
  • json.dump(obj,fp)pythonデータをjson形式のデータに変換し、ファイルに保存する
    #dump      1  python     json  2 json        
    with open('json.txt','w+') as f:
        json.dump(dict1,ensure_ascii=False,fp=f)
    #   dict1      json  ,      json.txt 
    
  • json.load(fp)ファイルからjsonデータを読み出しpython形式に変換するデータ
    with open('json.txt','r+') as f:
        res3 = json.load(fp=f)
    # json.txt   json       ,     python    ,res3       python