为什么print(new_data[0])只会打印出json文件的第一个字符?

2024-09-29 01:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图打印这个json文件的第一个对象,但它只打印它的第一个字符。你知道吗

这是我的密码:

response = requests.get("http://jsonplaceholder.typicode.com/users")
data = response.json()
new_data = json.dumps(data, indent = 2)
print(str(new_data[0]))

我希望的结果是:

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    }

实际结果:

[

Tags: 文件对象comjsonhttp密码newdata
3条回答

你知道吗json.dump文件回应的第一个要素:

import json

response = requests.get("http://jsonplaceholder.typicode.com/users")
data = response.json()
first_elem = json.dumps(data[0], indent=2)
print(first_elem)

你知道吗json.dumps文件结果是一个字符串。你知道吗

通过执行[0]打印字符串的第一个单词

对于所需的输出,请执行以下操作:

print(new_data)

显然response.json()已经是一个词汇了。你知道吗

所以如果你尝试first_element = data[0],你会得到你想要的。你知道吗

然后,如果你想让它变得漂亮:

json.dumps(first_element, indent = 2)

如果希望JSON对象的行为类似于dictionary,请查看

json.loads

https://docs.python.org/2/library/json.html

此外: What's the best way to parse a JSON response from the requests library?

相关问题 更多 >