从字符串中获取某些信息

时间:2015-08-31 06:58:12

标签: python

我是python的新手,因为我想知道如何从这个字符串中获取estimatedWaitrouteName

{
  "lastUpdated": "07:52",
  "filterOut": [],
  "arrivals": [
    {
      "routeId": "B16",
      "routeName": "B16",
      "destination": "Kidbrooke",
      "estimatedWait": "due",
      "scheduledTime": "06: 53",
      "isRealTime": true,
      "isCancelled": false
    },
    {
      "routeId":"B13",
      "routeName":"B13",
      "destination":"New Eltham",
      "estimatedWait":"29 min",
      "scheduledTime":"07:38",
      "isRealTime":true,
      "isCancelled":false
    }
  ],
  "serviceDisruptions":{
    "infoMessages":[],
    "importantMessages":[],
    "criticalMessages":[]
  }
}

然后将其保存到另一个字符串中,该字符串将显示在raspberry pi 2的lxterminal上。我希望只将B16的'routeName'保存到字符串中。我该怎么做?

2 个答案:

答案 0 :(得分:0)

您只需要对对象进行反序列化,然后使用索引来访问所需的数据。

要仅查找B16条目,您可以过滤到达列表。

import json
obj = json.loads(json_string)

# filter only the b16 objects
b16_objs = filter(lambda a: a['routeName'] == 'B16',  obj['arrivals'])

if b16_objs:
    # get the first item
    b16 = b16_objs[0]
    my_estimatedWait = b16['estimatedWait']
    print(my_estimatedWait)

答案 1 :(得分:0)

您可以使用string.find()来获取这些值标识符的索引 并提取它们。

示例:

def get_vaules(string):
    waitIndice = string.find('"estimatedWait":"')
    routeIndice = string.find('"routeName":"')
    estimatedWait = string[waitIndice:string.find('"', waitIndice)]
    routeName = string[routeIndice:string.find('"', routeIndice)]
    return estimatedWait, routeName

或者你可以反序列化json对象(强烈推荐)

import json

def get_values(string):
    jsonData = json.loads(string)
    estimatedWait = jsonData['arrivals'][0]['estimatedWait']
    routeName = jsonData['arrivals'][0]['routeName']
    return estimatedWait, routeName

Parsing values from a JSON file using Python?