[英]How to convert jsonify string to json in python?
I have a jsonify string as follows.我有一个 jsonify 字符串如下。 I have created this string using dart (Flutter).我使用 dart (Flutter) 创建了这个字符串。 My dart code is as follows.我的dart代码如下。
var stud_data = {"name": "John", "id": "2021MS", "total_marks": 493};
String encoded_data = base64Url.encode(utf8.encode(stud_data.toString()));
encoded_data contains "e25hbWU6IEpvaG4sIGlkOiAyMDIxTVMsIHRvdGFsX21hcmtzOiA0OTN9 " encoded_data 包含“e25hbWU6IEpvaG4sIGlkOiAyMDIxTVMsIHRvdGFsX21hcmtzOiA0OTN9”
I have to convert it to json in python.我必须将它转换为 python 中的 json。
I tried following code to convert in json using python.我尝试使用以下代码在 json 中使用 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.错误对我来说很明显,但我不知道如何解决。
As everyone has mentioned, you don't have a valid json string there.正如每个人都提到的,您那里没有有效的 json 字符串。 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.您不这样做的原因是因为您没有将 dart object 转换为 json。您只是将其转换为字符串。 Change your dart code to:将您的 dart 代码更改为:
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:这样做会给你一个有效的 json 字符串,当转换为 base64 时,最终将是:
eyJuYW1lIjoiSm9obiIsImlkIjoiMjAyMU1TIiwidG90YWxfbWFya3MiOjQ5M30=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.