Storing a string in a python json object

I read many questions regarding this but could not find any with str.

I got a long string of 16 bytes of name followed by 4 bytes of number and repeated for N number of people. An example as shown below:

* edit: 1) string is msg

2) added a microphone to the intended output

msg = 'George\0\0\0\0\0\0\0\0\0\0' + '0095' + 'Mikeeeeeeeeeeee\0' + '0100' + 'Kelly\0\0\0\0\0\0\0\0\0\0\0' + '0000'

      

And now I need to store this data in a json object. I've tried a loop, but it always overwrites the stored data before. I want something that works like below, but for a longer string, because it writes msg [start: end] for all data completely lagging behind.

data = {}
data[msg[0:16]] = {
    "marks" : msg[16:20]
}
data[msg[20:36]] = {
    "marks" : msg[36:40]
}
data[msg[40:56]] = {
    "marks" : msg[56:60]
}

      

estimated output:

{
"George\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000": {
    "marks": "0095"
    }, 
"Kelly\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000": {
    "marks": "0000"
    },
 "Mikeeeeeeeeeeee\u0000": {
    "marks": "0100"
    }
}

      

thank

+3


source to share


2 answers


Assuming you want all the object details, i.e. George, Mike and Kelly in yours data

, and you msg have length 60 only when you access 76 and beyond .. so to start adding objects. You should nest the json according to what you want as the output, e.g .:

length = len(msg)
i = 0
data = {}
while i < length:
    data[msg[i:i+16]] = {"marks" : msg[i+16:i+20]}
    i += 20
print data

      

Output:



{'George\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00': {'marks': '0095'}, 'Mikeeeeeeeeeeee\x00': {'marks': '0100'}, 'Kelly\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00': {'marks': '0000'}}

      

Hope it helps

+2


source


import re
dict(re.findall(r'(\D+)(\d{4})', string))

      

It will return a response like ..



{'George\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00': '0095', 'Kelly\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00': '0000', 'Mikeeeeeeeeeeee\x00': '0100'} 

      

Once you got this as a dict, this can be changed to whatever format you want.

+1


source







All Articles