我基本上有一个文件,它是json中的响应,但是我可以将其视为文件中的字符串行。我需要将键的某个值替换为动态值,例如,取值,进行一些计算并替换为该计算值。
例如(日期更改为+1):
"dateFrom":"Jun 24, 2018 10:00:34 AM"
至"dateFrom":"Jun 25, 2018 10:00:34 AM"
示例字符串为:
line = {"Num":"ML3","dateFrom":"Jun 24, 2018 10:00:34 AM","Val":"mean to","dateTo":"Jun 27, 2018 10:00:34 AM","requestInfo":{"requestIdentifier":"7cecc67d"}}
我试图通过使用如下正则表达式来解决此问题(“ TEST”)是伪值,但是我必须取date
并替换为date+1
:
lt = re.sub(r'dateFrom|dateTo.*":(.*AM|PM)(.*)",',"TEST", line, re.IGNORECASE)
最终没有正确输出。
预期:
line = {"Num":"ML3","dateFrom":"Jun 25, 2018 10:00:34 AM","Val":"mean to","dateTo":"Jun 28, 2018 10:00:34 AM","requestInfo":{"requestIdentifier":"7cecc67d"}}
我们非常感谢您的帮助。
谢谢。
样本数据为:
{"lAttributes":[{"Identifier":{"newIdentifier":{"DDline":"BM","guideIdDate":"Jun 25, 2018 12:00:00 AM","guideNo":"MM","suffix":"A"},"origin":"FRY","destination":"DZ"},"guideOwner":"VX","guideRegistration":"DD","guideType":"44","bestDepartureStatus":"S","bestArrivalTime":"Jun 25, 2018 6:00:00 AM","bestArrivalStatus":"S","bestDepartureTime":"Jun 25, 2018 5:00:00 AM","compartments":[{"code":"DD","guideCapacity":8,"guideBooked":0,"guideForecast":0},{"code":"DD","guideCapacity":10,"guideBooked":0,"guideForecast":0},{"code":"DD","guideCapacity":32,"guideBooked":0,"guideForecast":0},{"code":"DD","guideCapacity":24,"guideBooked":0,"guideForecast":0}]}]}
答案 0 :(得分:0)
您可以像这样为字典键分配一个值:
from datetime import datetime, timedelta
line = {"Num":"ML3","dateFrom":"Jun 24, 2018 10:00:34 AM","Val":"mean to","dateTo":"Jun 27, 2018 10:00:34 AM","requestInfo":{"requestIdentifier":"7cecc67d"}}
# Adds 1 day to dateFrom
new_date = datetime.strptime(line["dateFrom"], '%b %d, %Y %I:%M:%S %p') + timedelta(days=1)
# Formats new date as a string and assigns it to dictionary key
line["dateFrom"] = datetime.strftime(new_date, '%b %d, %Y %I:%M:%S %p')
print(line)
>>>{'Num': 'ML3', 'dateFrom': 'Jun 25, 2018 10:00:34 AM', 'Val': 'mean to', 'dateTo': 'Jun 27, 2018 10:00:34 AM', 'requestInfo': {'requestIdentifier': '7cecc67d'}}
如果您需要将json字符串表示形式转换为字典(这在您的问题中有点不清楚),则可以使用json
库:
import json
line = '{"Num":"ML3","dateFrom":"Jun 24, 2018 10:00:34 AM","Val":"mean to","dateTo":"Jun 27, 2018 10:00:34 AM","requestInfo":{"requestIdentifier":"7cecc67d"}}'
line = json.loads(line)