I've read a lot of question regarding this but couldn't find any with str.
I got a long str consisting 16 bytes of name followed by 4 bytes of number and repeated for N number of people. Example as below :
*edit : 1)string is msg
2)added mike into 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 these data into json object. I've tried loop but it always rewrites the stored data before. I want something that works as below but for a lot longer string since writing msg[start:end] for every data is completely retarded.
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]
}
intended 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"
}
}
Thanks
Assuming you want all of the object details i.e. George, mike and kelly in your data and you msg is of length 60 only while you are accessing 76 and onwards.. therefore to start appending you objects. You should make a nested json according to what you what you want as output result like:
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 this helps
import re
dict(re.findall(r'(\D+)(\d{4})', string))
It will return 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'}
As you got this as dict now, This can be changed in whatever format you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With