无法修复JSONDecodeError:无效的控制字符

时间:2019-04-23 20:28:58

标签: python json pyspark

我有一个json文件,其中包含以下内容:

#create test.json and add content
dbutils.fs.put("test.json",'{"type": "abc","project_id": "abc","private_key_id": "123","private_key": "-----BEGIN PRIVATE KEY----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCJ05O/Ke3tGA96\n-----END PRIVATE KEY-----\n","client_email": "abc@gmail.com","client_id": "345","auth_uri": "https://accounts.abc.com/o/oauth2/auth","token_uri": "https://abc","auth_provider_x509_cert_url": "https://abc","client_x509_cert_url": "https://abcrobot/v1/metadata/x509"}'

#Read test.json
json.loads(test.json)

#Error
JSONDecodeError: Invalid control character 

我在做什么错了?

2 个答案:

答案 0 :(得分:1)

不要手动生成JSON;让json.dumps为您做。这样可以确保私钥中出现的换行符正确编码。

config = {
    "type": "abc",
    "id": "t1-2-3",
    "private_key_id": "123",
    "private_key": "-----BEGIN PRIVATE KEY----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwkO/V+WyyrmTFVFoDN9sN1+AL+KX/IB3y\nZqLJVPGCdQ1l+TlZXbFKFYMwo/Ca4N8g4sy7ZH/9UcqKTxawyqrh7dPcRWWI\nyvAWaEJVCtZhw+Hp4fkmWdoi\n-----END PRIVATE"
}

dbutils.fs.put("test.json", json.dumps(config))

with open("test.json") as f:
    config2 = json.load(f)

答案 1 :(得分:0)

这种情况发生时,找出错误所在的简单方法是使用JSON验证程序,例如this one

在这种情况下,您缺少"和字符串的结尾,这是正确的方法:

dbutils.fs.put("test.json",'{"type": "abc","id": "t1-2-3","private_key_id":"123","private_key": "-----BEGIN PRIVATE KEY----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwkO/V+WyyrmTFVFoDN9sN1+AL+KX/IB3y\nZqLJVPGCdQ1l+TlZXbFKFYMwo/Ca4N8g4sy7ZH/9UcqKTxawyqrh7dPcRWWI\nyvAWaEJVCtZhw+Hp4fkmWdoi\n-----END PRIVATE" }'