如何在Python中将Dart(Flutter)生成的Base64URL编码字符串转换为JSON?
The Root Cause
That JSONDecodeError happens because Dart's Map.toString() doesn't produce valid JSON—it outputs a Dart-specific string representation of the map, not the standard JSON format. For your example, the decoded string looks like this:
{name: John, id: 2021MS, total_marks: 493}
Notice the non-compliant parts:
- Keys like
namedon’t have required double quotes - String values like
Johnalso lack double quotes
Python’s JSON parser enforces strict compliance with the JSON spec, hence the error.
Solutions
1. Fix the Dart Encoding (Recommended)
The cleanest fix is to generate a proper JSON string in Dart first, then encode it to Base64URL. This ensures compatibility with any JSON parser:
import 'dart:convert'; var stud_data = {"name": "John", "id": "2021MS", "total_marks": 493}; // Serialize map to valid JSON string first String jsonString = jsonEncode(stud_data); // Encode the JSON string to Base64URL String encoded_data = base64Url.encode(utf8.encode(jsonString));
With this change, the decoded string in Python will be valid JSON, and your original Python code will work without modifications.
2. Patch the Decoded String in Python (If You Can't Modify Dart Code)
If you’re stuck with the existing Base64URL string, you can convert the Dart-style map string to valid JSON using regex:
from base64 import urlsafe_b64decode import json import re stud_data_64 = "e25hbWU6IEpvaG4sIGlkOiAyMDIxTVMsIHRvdGFsX21hcmtzOiA0OTN9" # Decode the Base64URL string decoded_str = urlsafe_b64decode(stud_data_64).decode('utf-8') # Convert Dart map string to valid JSON: # 1. Add double quotes to unquoted keys fixed_json = re.sub(r'(\w+):', r'"\1":', decoded_str) # 2. Add double quotes to unquoted string values (skip numbers) fixed_json = re.sub(r':\s*([a-zA-Z0-9_]+)([,}])', r': "\1"\2', fixed_json) # Now parse the fixed JSON stud_data_json = json.loads(fixed_json) print(stud_data_json) # Output: {'name': 'John', 'id': '2021MS', 'total_marks': 493}
Note: This regex workaround works for your specific example, but it might fail if your Dart strings contain special characters (like colons or commas). Always prefer fixing the Dart encoding if possible.
Why Your Original Python Code Failed
When you decoded the Base64URL string, you got a Dart-specific map representation instead of valid JSON. Python’s json.loads() expects property names (keys) to be enclosed in double quotes, which the decoded string didn’t have—hence the Expecting property name enclosed in double quotes error.
内容的提问来源于stack exchange,提问作者Sumit Kumar

