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

    psycopg2: insert multiple rows with one query

    12 answers

    NUMPYNUMPY

    How to convert Nonetype to int or string?

    12 answers

    NUMPYNUMPY

    How to specify multiple return types using type-hints

    12 answers

    NUMPYNUMPY

    Javascript Error: IPython is not defined in JupyterLab

    12 answers

    News


    Wiki

    Python OpenCV | cv2.putText () method

    numpy.arctan2 () in Python

    Python | os.path.realpath () method

    Python OpenCV | cv2.circle () method

    Python OpenCV cv2.cvtColor () method

    Python - Move item to the end of the list

    time.perf_counter () function in Python

    Check if one list is a subset of another in Python

    Python os.path.join () method