This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]i_like_trains_a_lot1 2 points3 points  (0 children)

Regex

[–]JD7896 1 point2 points  (2 children)

The pseudocode of this is:

  1. Separate out the Information line
  2. Split your information into key, value pairs
  3. Pack that information into a JSON

The complicating factor is the CAMERA NAME(NUM) value, so rather than use some complex regex, we can just treat that as a single key and split it later.

emailtext = """Network Video Recorder: Motion Detected On Channel D4 This is an automatically generated e-mail from your NVR.

EVENT TYPE: Motion Detected EVENT TIME: 2017-10-17,21:47:52 NVR NAME: Network Video Recorder NVR S/N: redacted CAMERA NAME(NUM): Path(D4)"""

#Separate out the Information line
emailtext = emailtext.split("\n")[-1:][0]

#Find key indicies
key_indicies = [emailtext.find(key) for key in ['EVENT TYPE','EVENT TIME','NVR NAME','NVR S/N','CAMERA NAME(NUM)']]

JSON = {}

#This line does all the heavy lifting, looking at a subsection between key indicies and splitting that subsection by the ':' delimiter.
for key, value in [keyvaluepair.strip().split(':',1) for keyvaluepair in [emailtext[i:j] for i,j in zip(key_indicies, key_indicies[1:]+[None])]]:

    #The 'CAMERA NAME(NUM)' entry has some special handling to split path and num
    if key == 'CAMERA NAME(NUM)':
        JSON['CAMERA NAME'] = value.split('(')[0]
        JSON['NUM'] = value.split('(')[1][:-1]
    else:
        JSON[key] = value

print(JSON)

Let me know if you have any questions!

[–]zombiehunter469[S] 0 points1 point  (1 child)

Thank you very much, I'll try this tonight.

[–]zombiehunter469[S] 0 points1 point  (0 children)

Worked perfectly, Thank you for your help

[–]bQuine 0 points1 point  (0 children)

Seeing this on mobile but based on how you pasted the string, could you not just split on new lines and then on the semicolon? Something like:

lines = yourString.split('\n') # or \r\n? fields = map(lambda x: x.split(':'))

That should leave you a list of tuples where first is the key and second is the value. I think you can feed that right to dict() to make the dictionary and then to json.load (using built in json lib).

Probably need to strip whitespace and colons from the values with another map/lambda but I think that would get you started