JSON Library In Python - Loads/dumps/load/dump

 Using JSON library we can perform this main operation


Method

Description

dumps()

encoding to JSON objects

dump()

encoded string writing on file

loads()

Decode the JSON string

load()

Decode while JSON file read


Python to JSON (Encoding)

JSON Library of Python performs following translation of Python objects into JSON objects by default

PythonJSON
dictObject
listArray
unicodeString
number - int, longnumber – int
floatnumber – real
TrueTrue
FalseFalse
NoneNull


JSON to Python (Decoding)

JSON string decoding is done with the help of inbuilt method loads() & load() of JSON library in Python. Here translation table show example of JSON objects to Python objects which are helpful to perform decoding in Python of JSON string.

JSONPython
Objectdict
Arraylist
Stringunicode
number – intnumber - int, long
number – realfloat
TrueTrue
FalseFalse
NullNone



How to Convert String to JSON Object? When they send using request.data

{

"data": {

"title":"test" ,

"body":"hello json loads"}

}

my_json = request.data.decode('utf8').replace("'", '"')

meta_data_dict = json.loads(my_json)

How to Convert String to JSON Object? When they send using request.Form

json = {

"data": {

"title":"test" ,

"body":"hell json loads"}

}

json_of_metadata = request.form.to_dict(flat=False)

meta_data_from_json = json_of_metadata['json']

 meta_data_from_json_0 = meta_data_from_json[0]

str_meta_data_from_json_0 = str(meta_data_from_json_0)

meta_data_dict = json.loads(str_meta_data_from_json_0)


How to Convert Special Character String to JSON Object? When they send using request.data

{

"data": {

"title":"test" ,

"body":"%#&*^(()Q24 (nkdnmad,m 562651K:KW?QKW KS HS;qe'`1!0923;a,    kis  "}

}

my_json = request.data.decode('utf8')

meta_data_dict = json.loads(my_json)


How to Get / Request Binary Data

data = request.get_data()


How to Get / Request Files or Images

if 'image' in request.files:
        files.update({'image': request.files['image']})

if 'gallery' in request.files:

        files.update({'gallery': request.files.getlist('gallery')})

    if 'thumbnail' in request.files:

        files.update({'thumbnail': request.files['thumbnail']})


Comments

Popular posts from this blog

ERR: error parsing query: found influx, expected SELECT, DELETE, SHOW, CREATE, DROP, EXPLAIN, GRANT, REVOKE, ALTER, SET, KILL at line

How To Convert Html File/URL/String Into Image Using Python

How to get Full URL or get absolute url In Django