【问题标题】:Getting values from JSON using Python使用 Python 从 JSON 获取值
【发布时间】:2012-09-03 09:56:17
【问题描述】:

当我尝试从 JSON 字符串中检索值时,它给了我一个错误:

data = json.loads('{"lat":444, "lon":555}')
return data["lat"]

但是,如果我遍历数据,它会给我元素(latlon),而不是值:

data = json.loads('{"lat":444, "lon":555}')
    ret = ''
    for j in data:
        ret = ret + ' ' + j
return ret

返回:lat lon

我需要做什么才能获得latlon 的值? (444555

【问题讨论】:

  • 你的第一个例子对我有用。它给你的错误是什么?
  • (无关),你的第二个循环可以写成' '.join(data)
  • 在 Python 2.7 和 Bottle 中使用 GAE,它给了我 "INFO 2012-09-10 13:54:58,583 dev_appserver.py:2967] "POST /app/939393/position HTTP/1.1" 500 -" 在 GAE 日志控制台上
  • 错误回溯在这里可能很有用,因为第一部分的代码没问题。它不能抛出与问题相关的错误(至少对于 python 3.6),错误必须在导入或函数使用中(作为返回存在)

标签: python json simplejson


【解决方案1】:

如果您想遍历字典的键和值,请执行以下操作:

for key, value in data.items():
    print key, value

【讨论】:

    【解决方案2】:

    它给你什么错误?

    如果你这样做:

    data = json.loads('{"lat":444, "lon":555}')
    

    然后:

    data['lat']
    

    不应该给你任何错误。

    【讨论】:

      【解决方案3】:

      使用 Python 从提供的 Json 中提取值

      Working sample:-
      
      import json
      import sys
      
      //load the data into an element
      data={"test1" : "1", "test2" : "2", "test3" : "3"}
      
      //dumps the json object into an element
      json_str = json.dumps(data)
      
      //load the json to a string
      resp = json.loads(json_str)
      
      //print the resp
      print (resp)
      
      //extract an element in the response
      print (resp['test1'])
      

      【讨论】:

        【解决方案4】:

        有一个 Py 库,它有一个模块,可以方便地访问类似 Json 的字典键值作为属性:https://github.com/asuiu/pyxtension 您可以将其用作:

        j = Json('{"lat":444, "lon":555}')
        j.lat + ' ' + j.lon
        

        【讨论】:

          【解决方案5】:

          使用您的代码,我会这样做。我知道选择了一个答案,只是提供了其他选项。

          data = json.loads('{"lat":444, "lon":555}')
              ret = ''
              for j in data:
                  ret = ret+" "+data[j]
          return ret
          

          当你以这种方式使用“for”时,你得到的是对象的键,而不是值,所以你可以通过使用键作为索引来获取值。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-04-21
            • 1970-01-01
            • 2017-03-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多