Home > Enterprise >  How to convert jsonify string to json in python?
How to convert jsonify string to json in python?

Time:10-09

I have a jsonify string as follows. I have created this string using dart (Flutter). My dart code is as follows.

 var stud_data = {"name": "John", "id": "2021MS", "total_marks": 493};
 String encoded_data = base64Url.encode(utf8.encode(stud_data.toString())); 

encoded_data contains "e25hbWU6IEpvaG4sIGlkOiAyMDIxTVMsIHRvdGFsX21hcmtzOiA0OTN9 "

I have to convert it to json in python.

I tried following code to convert in json using python.

from base64 import urlsafe_b64decode
import json
stud_data_64="e25hbWU6IEpvaG4sIGlkOiAyMDIxTVMsIHRvdGFsX21hcmtzOiA0OTN9"
stud_data=urlsafe_b64decode(string).decode('utf-8')
stud_data_json = json.loads(stud_data)

It results in the following error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

The error is clear to me, but I don't know how to solve it.

CodePudding user response:

As everyone has mentioned, you don't have a valid json string there. The reason that you don't is because you're not converting your dart object to json. You're just converting it to a string. Change your dart code to:

String encoded_data = base64Url.encode(utf8.encode(jsonEncode(stud_data)));

Doing that will give you a valid json string which when converted to base64 will end up being:

eyJuYW1lIjoiSm9obiIsImlkIjoiMjAyMU1TIiwidG90YWxfbWFya3MiOjQ5M30=

CodePudding user response:

A second alternative is if you do convert the dart object into a string always use json.dumps like so.

stud_data_64="e25hbWU6IEpvaG4sIGlkOiAyMDIxTVMsIHRvdGFsX21hcmtzOiA0OTN9"
stud_data=urlsafe_b64decode(stud_data_64).decode('utf-8')
stud_data_json = json.loads(json.dumps(stud_data))
print(stud_data_json)

Output: {name: John, id: 2021MS, total_marks: 493}

  • Related