Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing string into json object python

Tags:

python

json

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

like image 666
fieq.fikri Avatar asked Feb 18 '26 18:02

fieq.fikri


2 Answers

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

like image 71
warl0ck Avatar answered Feb 20 '26 06:02

warl0ck


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.

like image 28
xrage Avatar answered Feb 20 '26 06:02

xrage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!