基于值替换json结构中的数据

时间:2017-10-16 20:17:46

标签: python json

我有一个文件(myfile.txt),格式如下

{"click_id": 124, "created_at": "2017-02-03T10:51:33", "product_id": 97373, "product_price": 320.50, "user_id": 1, "ip": "null"}
{"click_id": 125, "created_at": "2017-10-03T10:52:33", "product_id": 96373, "product_price": 20.50, "user_id": 1, "ip": "London"}
{"click_id": 126, "created_at": "2017-10-03T11:50:33", "product_id": 88373, "product_price": 220.50, "user_id": 2, "ip": "London"}

功能:

def get_status(self, user_id, date):
        for rec in self.RECORDS:
            if rec['user_id'] == user_id and dt.datetime.strptime(rec['created_at'],'%Y-%m-%dT%H:%M:%S') == date:
                return rec['status']

上述函数根据提供的输入返回状态。状态可以是"Valid", "Invalid", "Old", "New"

有没有办法解析myfile.txt并添加通过匹配函数{{1中传递的statuscreated_at返回的user_id键使用get_status中的那个?

输出(myfile.txt):

myfile.txt

1 个答案:

答案 0 :(得分:0)

首先,请注意您的文件无效JSON。由于它是一个列表,因此您的对象应包含在数组中。

这将导入文件,解析并将其写入同一文件。您只需要输入逻辑来替换for循环中的状态。

import json

data_file = "myfile.txt"
data = open(data_file, "r+") #r+ so the file can be both read and written to
parsed_data = json.load(data)

for obj in parsed_data:
    obj['status'] = "modified status" #replace the status here according to your logic

new_data = json.dumps(parsed_data)
data.seek(0)
data.write(new_data)
data.truncate() #not entirely necessary
data.close()