简体   繁体   English

从字符串中获取某些信息

[英]Getting certain information from string

I'm new to python as was wondering how I could get the estimatedWait and routeName from this string.我是 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":[]
  }
}

And then save this to another string which would be displayed on the lxterminal of the raspberry pi 2. I would like only the 'routeName' of B16 to be saved to the string.然后将其保存到另一个字符串中,该字符串将显示在lxterminal pi 2 的lxterminal上。我只想将 B16 的“routeName”保存到字符串中。 How do I do that?我怎么做?

You just have to deserialise the object and then use the index to access the data you want.您只需要反序列化对象,然后使用索引来访问您想要的数据。

To find only the B16 entries you can filter the arrivals list.要仅查找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)

You can use string.find() to get the indices of those value identifiers and extract them.您可以使用 string.find() 来获取这些值标识符的索引并提取它们。

Example:例子:

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

Or you could just deserialize the json object (highly recommended)或者你可以反序列化 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? 使用 Python 从 JSON 文件中解析值?

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

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