Python 从字符串中获取某些信息

Python 从字符串中获取某些信息,python,Python,我是python新手,我想知道如何从这个字符串中获得estimatedWait和routeName { "lastUpdated": "07:52", "filterOut": [], "arrivals": [ { "routeId": "B16", "routeName": "B16", "destination": "Kidbrooke", "estimatedWait": "due", "scheduledT

我是python新手,我想知道如何从这个字符串中获得
estimatedWait
routeName

{
  "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的
lx终端上。我只希望B16的“routeName”保存到字符串中。如何实现这一点?

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

要仅查找
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)
可以使用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对象(强烈建议)


您确定这是整个字符串吗?因为末尾缺少括号。如果这是有效的JSON,您可以将其反序列化为python对象:
obj=JSON.loads(yourstring)
还有更多。这是while字符串。{“lastUpdated”:“08:09”,“filterOut”:[],“arrivals”:[{“routeId”:“B13”,“routeName”:“B13”,“destination”:“New Eltham”,“estimatedWait”:“1分钟”,“scheduledTime”:“07:10”,“isRealTime”:true,“isCancelled”:false},{“routeId”:“B13”,“destination”:“New Eltham”,“estimatedWait”:“29分钟”,“scheduledTime”:“07:38”,“isRealTime”:true,“isCancelled”:false}],“serviceDisruptions”:{“infoMessages”:[],“importantMessages”:[],“criticalMessages”:[]}}如果我想要routeName,我将如何处理这个python对象?请编辑您的问题以更新类似这样的信息。您需要哪个
estimatedWait
routeName
?就第一个?
import json

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