You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中将Dart(Flutter)生成的Base64URL编码字符串转换为JSON?

Fix: Parsing Dart-generated Base64URL String to JSON in Python

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 name don’t have required double quotes
  • String values like John also 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:37:31