Change language

JSON formatting in Python

|

Javascript Object Notation, or JSON for short, is a lightweight data interchange format. It encodes Python objects as JSON strings and decodes JSON strings into Python objects.

  • Many of the APIs like Github . send your results in this format. JSON is probably the most widely used for communication between a web server and a client in an AJAX application, but is not limited to this problem area.
  • For example, if you are trying to create an exciting project like this , we need to format the JSON output to get the results we want. So let’s dive into the json module that Python offers for formatting JSON output.

functions

  • json.dump (obj, fileObj) : Serializes as a JSON stream for.
  • json.dumps (obj) : Serializes as a JSON string .
  • json.load (JSONfile) : deserializes to a Python object.
  • json.loads (JSONfile) : deserializes (type: string) into a Python object.
  • Classes

  • JSONEncoder: encoder class for converting Python objects to JSON.
  • JSONDecoder: decoder class for converting JSON file to Python obj.
  • Conversions are based on this conversion table .


    Implementation

    encoding
    We will use dump (), dumps () and the JSON.Encoder class.

    # The code will work 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 )))))

    Output:

     Using json.dump (): ["Hello", "Geeks"] Using json.dumps ( ): "" Using json.JSONEncoder (). Encode "" Using json.JSONEncoder (). Iterencode [’" "’] 

    Decoding
    We will use load (), load () and the JSON.Decoder class.

    # Code will work 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}’ )))

    Output:

     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) 

    Link :

    This article is courtesy of  Sri Sanket Uppalapati . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

    Shop

    Learn programming in R: courses

    $

    Best Python online courses for 2022

    $

    Best laptop for Fortnite

    $

    Best laptop for Excel

    $

    Best laptop for Solidworks

    $

    Best laptop for Roblox

    $

    Best computer for crypto mining

    $

    Best laptop for Sims 4

    $

    Latest questions

    NUMPYNUMPY

    Common xlabel/ylabel for matplotlib subplots

    12 answers

    NUMPYNUMPY

    How to specify multiple return types using type-hints

    12 answers

    NUMPYNUMPY

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    12 answers

    NUMPYNUMPY

    Flake8: Ignore specific warning for entire file

    12 answers

    NUMPYNUMPY

    glob exclude pattern

    12 answers

    NUMPYNUMPY

    How to avoid HTTP error 429 (Too Many Requests) python

    12 answers

    NUMPYNUMPY

    Python CSV error: line contains NULL byte

    12 answers

    NUMPYNUMPY

    csv.Error: iterator should return strings, not bytes

    12 answers

    News


    Wiki

    Python | How to copy data from one Excel sheet to another

    Common xlabel/ylabel for matplotlib subplots

    Check if one list is a subset of another in Python

    sin

    How to specify multiple return types using type-hints

    exp

    Printing words vertically in Python

    exp

    Python Extract words from a given string

    Cyclic redundancy check in Python

    Finding mean, median, mode in Python without libraries

    cos

    Python add suffix / add prefix to strings in a list

    Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

    Python - Move item to the end of the list

    Python - Print list vertically