简体   繁体   English

在Python中从JSON文件读取

[英]Reading from JSON file in Python

The variable data has the following JSON 变量数据具有以下JSON

{
   "destination_addresses" : [ "Stade Leopold Sedar Senghor, Route de Yoff, Dakar, Senegal" ],
   "origin_addresses" : [ "Unnamed Road, Dakar, Senegal" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "13.0 km",
                  "value" : 13007
               },
               "duration" : {
                  "text" : "23 mins",
                  "value" : 1383
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

I then run the following code: 然后,我运行以下代码:

parsed =  json.loads(data)

I want to store distance "text" and "value", and duration "text" and "value" and "status" into variables in python. 我想将距离“文本”和“值”以及持续时间“文本”,“值”和“状态”存储到python变量中。 I tried the following code but it did not work: 我尝试了以下代码,但没有成功:

dist = int(parsed['rows']['elements']['distance']['value'])

But I am getting an error 但是我遇到一个错误

元素是列表,因此您需要指定一个索引:

dist = int(parsed['rows'][0]['elements'][0]['distance']['value'])

Here you have working code. 这里有工作代码。 I have just changed a bit and it works fine. 我刚刚做了些改动,效果很好。 The access to dictionary it a little bit confusing. 访问字典有点混乱。 I will try to explain. 我会尽力解释。 The json.dumps serialize a str to a json obj. json.dumps将str序列化为json obj。 Here for more information. 在这里获取更多信息。 json.dumps json.dumps

 data ={
   "destination_addresses" : [ "Stade Leopold Sedar Senghor, Route de Yoff, Dakar, Senegal" ],
   "origin_addresses" : [ "Unnamed Road, Dakar, Senegal" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "13.0 km",
                  "value" : 13007
               },
               "duration" : {
                  "text" : "23 mins",
                  "value" : 1383
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}


data_string = json.dumps(data)
parsed =  json.loads(data_string)

print parsed['rows'][0]['elements'][0]['distance']['text']

When you have a list into a dictionary first of all you have to refer the index(an integer) that you want to access and then the dictionary index with the name('string'). 当您在字典中有一个列表时,首先必须引用您要访问的索引(整数),然后再使用名称('string')引用字典索引。 As you can see in the last line of the code. 如您在代码的最后一行中所见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM