I want to retrieve certain values from a list object that contains strings and dictionaries. If the dictionary equals a certain name I want to add it to the output file.
First I read in a json file which looks like this:
{
"event": "user",
"timestamp": {
"$numberDouble": "1671459681.4369426"
},
"metadata": {
"model_id": "125817626"
},
"text": "hello",
"parse_data": {
"intent": {
"name": "greet",
"confidence": {
"$numberDouble": "1.0"
}
},
I have events that equal "user" and those that equal "bot". What I want to have in the end is an output file that has user and bot in each line. At the beginning of the line I also want to have the timestamp, formatted in human readable time, and at the end the text like
2020-03-13 12:11:25 user: hello
2020-03-13 12:11:28 bot: Hi
However, I do not know how to access the value of "timestamp", format it and then print it together with "user" and "text" in one line.
What I have done so far is that:
import json
from datetime import datetime
f = open('1234.json')
data = json.load(f)
all_events = [e for e in data.get('events', list()) if e.get('event')=='user' or e.get('event')=='bot']
file_object = open('1234.txt', 'a')
for event in all_events:
file_object.write(str(event.get('timestamp')) " " event.get('event') ": " event.get('text', '') "\n")
f.close()
What I get with this is:
{'$numberDouble': '1671459681.4369426'} user: hello
I know that I can use something like this to format the time
ts = int("1584101485")
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
But I do not know how to wrap this in my file_object.write command
CodePudding user response:
Instead of getting the timestamp
key's value, you need to parse the $numberDouble
value inside of the timestamp
dictionary:
file_object.write(
datetime.utcfromtimestamp(float(event['timestamp']['$numberDouble'])).strftime('%Y-%m-%d %H:%M:%S') " " event.get('event') ": " event.get('text', '') "\n"
)