I have the following, very basic code that throws; TypeError: the JSON object must be str, not 'bytes'

import requests
import json

url = 'my url'
user = 'my user'
pwd = 'my password'

response = requests.get(url, auth=(user, pwd))

if(myResponse.ok):
    Data = json.loads(myResponse.content)

我try 将decode设置为数据变量,如下所示,但它会抛出相同的错误;jData = json.loads(myResponse.content).decode('utf-8')

有什么建议吗?

推荐答案

json.loads(myResponse.content.decode('utf-8'))

你只是把它放错了顺序,无辜的错误.


(深入回答).正如WIM礼貌地指出的那样,在某些罕见的情况下,他们可以 Select UTF-16或UTF-32.这些情况将不太常见,因为在这种情况下,开发人员会有意识地决定丢弃宝贵的带宽.因此,如果遇到编码问题,可以将utf-8更改为16、32等.

There are a couple of solutions for this. You could use request's built-in .json() function:

myResponse.json()

Or, you could opt for character detection via chardet. Chardet is a library developed based on a study. The library has one function: detect. Detect can detect most common encodings and then use them to encode your string with.

import chardet
json.loads(myResponse.content.decode(chardet.detect(myResponse.content)["encoding"]))

Json相关问答推荐

如何使用JQ有条件 Select 值

如何使用JQ将JSON字符串替换为解析后的类似功能?

在Vega中如何通过滑块改变条形图的宽度

PowerShell女士:如何处理json对象?

迭代powershell双维json对象

APIM 生成 JsonArray 到 EventHub

Groovy JsonBuilder 在for循环中添加数组元素

使用 TypeScript 接口时如何修复未定义错误?

使用 jq 和脚本 bash 映射两个 json

JOLT JSON 将值从一对多转换为一对一

传统编程语言等价于动态 SQL

我无法在 Go - Gin 中解析日期/时间

在 postgresql 中将行转换为 json 对象

将 JSON 数据导入 Google 表格

如何在java中比较来自JsonObject的空值

我们可以使用 JSON 作为数据库吗?

带有方法参数的 WCF webHttpBinding 错误. 最多可以在没有包装元素的情况下序列化一个主体参数

使用 Python 3 读取 JSON 文件

如何在 React js 中解析本地 JSON 文件?

Wordpress JsonAPI - 在此服务器上找不到 /wp-json/