Python中的JSON格式

null

Javascript对象表示法缩写为JSON,是一种轻量级的数据交换格式。它将Python对象编码为JSON字符串,并将JSON字符串解码为Python对象。

  • 许多API都像 github .以这种格式发送结果。JSON可能最广泛地用于AJAX应用程序中web服务器和客户机之间的通信,但不限于该问题域。
  • 例如,如果你正在尝试建立一个令人兴奋的项目,比如 ,我们需要格式化JSON输出以呈现必要的结果。因此,让我们深入探讨 json Python为格式化JSON输出提供的模块。

功能

  • json。转储(obj,fileObj) :序列化 obj 作为JSON格式的流 fileObj .
  • json。转储(obj) :序列化 obj 作为JSON格式的字符串。
  • json。加载(JSONfile) :反序列化 JSONfile 到Python对象。
  • json。加载(JSONfile) :反序列化 JSONfile (输入:string)到Python对象。

    班级

  • JSONEncoder: 将Python对象转换为JSON格式的编码器类。
  • JSONDecoder: 将JSON格式文件转换为Python obj的解码器类。

    转换基于此 换算表 .

    实施

    编码 我们将使用dump()、dumps()和JSON。编码器类。

    #Code will run in Python 3
    from io import StringIO
    import json
    fileObj = StringIO()
    json.dump([ "Hello" , "Geeks" ], fileObj)
    print ( "Using json.dump(): " + str (fileObj.getvalue()))
    class TypeEncoder(json.JSONEncoder):
    def default( self , obj):
    if isinstance (obj, type ):
    return str (obj)
    print ( "Using json.dumps(): " + str (json.dumps( type ( str ), cls = TypeEncoder)))
    print ( "Using json.JSONEncoder().encode" +
    str (TypeEncoder().encode( type ( list ))))
    print ( "Using json.JSONEncoder().iterencode" +
    str ( list (TypeEncoder().iterencode( type ( dict )))))

    
    

    输出:

    Using json.dump(): ["Hello", "Geeks"]
    Using json.dumps(): ""
    Using json.JSONEncoder().encode""
    Using json.JSONEncoder().iterencode['""']
    

    解码 我们将使用load()、loads()和JSON。解码器类。

    #Code will run in Python 3
    from io import StringIO
    import json
    fileObj = StringIO( '["Geeks for Geeks"]' )
    print ( "Using json.load(): " + str (json.load(fileObj)))
    print ( "Using json.loads(): " + str (json.loads( '{"Geeks": 1, "for": 2, "Geeks": 3}' )))
    print ( "Using json.JSONDecoder().decode(): " +
    str (json.JSONDecoder().decode( '{"Geeks": 1, "for": 2, "Geeks": 3}' )))
    print ( "Using json.JSONDecoder().raw_decode(): " +
    str (json.JSONDecoder().raw_decode( '{"Geeks": 1, "for": 2, "Geeks": 3}' )))

    
    

    输出:

    Using json.load(): ['Geeks for Geeks']
    Using json.loads(): {'for': 2, 'Geeks': 3}
    Using json.JSONDecoder().decode(): {'for': 2, 'Geeks': 3}
    Using json.JSONDecoder().raw_decode(): ({'for': 2, 'Geeks': 3}, 34)
    
    

    参考:

    本文由 斯里·桑凯斯·乌帕拉帕蒂 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

    如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

  • © 版权声明
    THE END
    喜欢就支持一下吧
    点赞11 分享