2015-08-31 121 views
-1

我是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":[] 
    } 
} 

,然后将此保存到这将显示在树莓派2的lxterminal我只喜欢B16的“routeName”保存到串另一个字符串。我怎么做?

+1

你确定这是整个字符串?因为最后没有括号。如果这是有效的JSON,你可以反序列化成一个python对象:'obj = json.loads(yourstring)' – cansik

+0

还有更多。这是字符串。 – Dike

+0

{“lastUpdated”:“08:09”,“filterOut”:[],“arrivals”:[{“routeId”:“B13”,“routeName”:“B13”,“destination”:“New Eltham”, “estimatedWait”:“1分钟”,“scheduledTime”:“07:10”,“isRealTime”:true,“isCancelled”:false},{“routeId”:“B13”,“routeName”:“B13”目的地“:”新Eltham“,”estimatedWait“:”29分钟“,”scheduledTime“:”07:38“,”isRealTime“:true,”isCancelled“:false}],”serviceDisruptions“:{”infoMessages“ [],“importantMessages”:[],“criticalMessages”:[]}} – Dike

回答

1

你只需要反序列化对象,然后使用索引来访问你想要的数据。

要仅查找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) 
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?