【问题标题】:why type(JSON) is str in python?为什么 type(JSON) 在 python 中是 str ?
【发布时间】:2020-02-18 21:29:49
【问题描述】:

我通过请求从 API 获得了一些数据:

r = requests.get(...)
a = r.text
print(type(a))
str2JSON = json.dumps(a,indent=4)
print(type(str2JSON))

结果是:

class 'str'
class 'str'

然后我尝试loads 而不是dumps

str2JSON_2 = json.loads(a)
print(type(str2JSON_2))

我上课list!!!

为什么会有这种行为?

如果你将一个字符串转储到 JSON 中并且你没有收到错误,这是否意味着 JSON 被很好地解析了?那不应该是一个 JSON 类吗?

【问题讨论】:

  • 问题中似乎没有包含您的结果
  • 您是不是要使用loads 而不是dumps
  • 输出是正确的,因为 dumps() 函数(如在 dump S 中)返回一个字符串,正如 dumps() 中的 S 所建议的那样。

标签: python json string


【解决方案1】:

您从请求中返回的是一个包含 JSON 编码值的 str 值。

dumps 采用 str 并生成 another 字符串,其中包含原始(JSON 编码)字符串的 JSON 编码版本。

您需要loads 将字符串解码成一个值。

json2str = json.loads(a,indent=4)  # name change to reflect the direction of the operation

考虑:

>>> s = '"foo"'  # A JSON string value
>>> json.dumps(s)
'"\\"foo\\""'
>>> json.loads(s)
'foo'

当然,字符串可以编码一个不是简单字符串的值:

>>> json.loads('3')  # Compare to json.loads('"3"') returning '3'
3
>>> json.loads('[1,2,3]')
[1,2,3]
>>> json.loads('{"foo": 6}')
{'foo': 6}

requests 不过,实际上并不要求您记住 dumpsloads 的方向(尽管您应该重点学习)。 Response 对象有一个 json 方法,可以为您解码 text 属性。

json2str = r.json()  # equivalent to json2str = json.loads(r.text)

【讨论】:

    【解决方案2】:

    您正在使用请求。它提供了您想要的convince method to parse your response as json(即它为您加载)a = r.json()。这样a 将是 JSON 对象,您可以稍后将其转储为字符串。那是假设您得到有效的 json 作为响应。

    这是一个例子

    import requests
    import json
    
    url = 'https://reqres.in/api/users' # dummy resposnse
    
    resp =  requests.get(url)
    my_json = resp.json()
    #print example user
    print(my_json['data'][0])
    json_string = json.dumps(my_json, indent=4)
    print(json_string)
    

    【讨论】:

    • 你在那里插入了什么:type(my_json)?
    • 自己尝试一下 :-)
    • 我做了:HTTPSConnectionPool(host='reqres.in', port=443) 超出最大重试次数等。我无法连接到该 API。
    • 它只是一个虚拟 api。如果由于某种原因您无法连接到它 - 请尝试使用您的 API url
    【解决方案3】:

    json.dumps 返回一个 JSON 格式的 Python 字符串对象。

    下面是def dumps的实际实现文件中可以注意到的语句

    """将obj序列化为JSON格式的str

    【讨论】:

      猜你喜欢
      • 2017-06-22
      • 2015-07-17
      • 1970-01-01
      • 2020-04-23
      • 2017-07-21
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多