user9727749
user9727749

Reputation:

How to convert data into JSON dictionary?

So I get a response and print it. The result is bytes:

payload = request.body
print (payload)
b'a=123&b=345&c=678&d=910'

I decode it, and the result is:

dataform = payload.decode('utf-8').replace("'", '"')
print(dataform, 'dataform')
a=123&b=345&c=678&d=910

I dumps it, and the result is:

result = json.dumps(dataform, indent=4, sort_keys=True)
print(result, 'result')
"a=123&b=345&c=678&d=910"

I loads it, and the result is:

jason = json.loads(result)
print(jason, 'jason')
a=123&b=345&c=678&d=910

I just want a normal json dictionary that I can refer to like data['string']. What am I doing wrong or not doing?

Upvotes: 0

Views: 155

Answers (3)

vczm
vczm

Reputation: 594

import json
from urllib.parse import parse_qs

payload = request.body
# b'a=123&b=345&c=678&d=910'

qs = parse_qs(payload.decode())
# {'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}

Convert list values and convert data into JSON

json.dumps({k: v[0] for k, v in qs.items()})
# '{"a": "123", "b": "345", "c": "678", "d": "910"}'

Upvotes: 1

Raniz
Raniz

Reputation: 11113

There's a few errors here.

First off, dumping to JSON and then loading it again does absolutely nothing (it does have a few side-effects, but that's not important here).

Secondly, and mainly, your input data isn't JSON - it's either a query string or, more likely, form-data.

You can try to parse it using the standard parse_qs in urllib.parse, but if that fails you'll have to look around for a library that can handle proper form data.

In [1]: from urllib.parse import parse_qs

In [2]: payload = b'a=123&b=345&c=678&d=910'

In [3]: dataform = payload.decode('utf-8').replace("'", '"')

In [4]: result = parse_qs(dataform)

In [5]: print(result)
{'a': ['123'], 'b': ['345'], 'c': ['678'], 'd': ['910']}

Upvotes: 1

Ihor Voronin
Ihor Voronin

Reputation: 154

At first, you need to convert the string (here, as the example, to the array, but you can use that you want)

data = [x.split('=') for x in data.split('&')]
>>> data
[['a', '123'], ['b', '345'], ['c', '678'], ['d', '910']]

And after this, you can easily create the dictionary.

dict = {key: value for (key,value) in data}
>>> dict
{'a': '123', 'c': '678', 'b': '345', 'd': '910'}

Or if you want to store numbers as int:

dict = {key: int(value) for (key,value) in data}
>>> dict
{'a': 123, 'c': 678, 'b': 345, 'd': 910}

Upvotes: 1

Related Questions