【问题标题】:Python get deep json valuePython 获取深度 json 值
【发布时间】:2018-08-10 05:42:30
【问题描述】:
  {
  "export": {
    "version": "3.4",
    "date": "2018-08-09T13:19:46Z",
    "groups": [
      {
        "name": "Templates"
      }
    ],
    "templates": [
      {
        "template": "Template OS",
        "name": "Template OS",
        "description": "",
        "groups": [
          {
            "name": "Datawhatiwant"
          }
        ],

这是 JSON 代码的相关部分,我想要值 datawhatiwant。 但是如果我使用print json_data["export"] 就会出现这个错误: TypeError: string indices must be integers 那么我怎样才能获得 datawhatiwant

【问题讨论】:

  • 你的json_data是从哪里得到的?
  • 您的 JSON 对象示例也不完整
  • 好像你有一个字符串。您需要使用json.loads 将字符串转换为python 对象
  • @Bakuriu 我已经在使用 json.loads
  • @t0m那你可能做错了。如果您向我们提供了您正在使用的实际代码,我们可能会在 2 分钟内告诉您问题出在哪里,但我们只能根据您提供的少量信息进行猜测

标签: python json


【解决方案1】:

你需要先解码json

import json

print(json.loads(json_data)["export"])

我认为应该会更好。

【讨论】:

  • 我已经解码了 json:req = requests.get(url, data=json.dumps(reg), headers=headers) json_data = json.loads(req.text) print json_data["export]
  • 好吧,如果你只打印 json_data,你会得到什么?我猜这将是一个字符串...
  • 这是来自 json 输出的相关部分:{u'jsonrpc': u'2.0', u'result': u'{"export":{"version":"3.4","date":"2018-08-10T06:15:39Z","groups":[{"name":"Templates"}],"templates":[{"template":"Template FS","name":"Template FS","description":"","groups":[{"name":"datawhatiwant"}]
  • 查看结果键的值。正如您的错误所声称的那样,它是一个字符串。这就是你需要给 json.loads()
  • 喜欢这个? print json.loads(json_data["result"][2])
猜你喜欢
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多