I have a .log file containing both text strings and json. For example:
A whole bunch of irrelevant text
2022-12-15 12:45:06, run: 1, user: james json:
[{"value": "30", "error": "8"}]
2022-12-15 12:47:36, run: 2, user: kelly json:
[{"value": "15", "error": "3"}]
More irrelevant text
My goal is to extract the json but keep it paired with the text that comes before it so that the two can be tied together. The keyword that indicates the start of a new section is run
. However, as shown in the example below, I need to extract the timestamp from the same line where run
appears. The character that indicates the end of a section is ]
.
My goal is to parse this text into a pandas dataframe like the following:
timestamp run user value error
2022-12-15 12:45:06 1 james 30 5
2022-12-15 12:47:36 2 kelly 15 8
3
Answers
To extract the json data and the timestamp from the text file, you can use Regex to search for the expression that indicates the start of a new section. In this case, the pattern you’re looking for is the time followed by the keyword "run". In Python this would look like:
`
Try:
Prints:
Sometimes people find regular expressions hard to follow or maintain, so I wrote pyparsing to make code that parses this kind of data easier to read. (This code uses the jsonValue parser from the jsonParser.py example in the pyparsing examples directory.) This may also be easier to modify in the future, if your data format changes.
Prints:
If you just want a pretty tabular output, littletable is much lighter weight than pandas (and can also do other simple tabular functions, such as CSV import/export):
littletable uses the rich package for table presentation.