using simplejson.dumps to encode a dictionary to json

A

Aaron

Hi there,

I am attempting to use simplejson.dumps to convert a dictionary to a json encoded string.

For some reason this doesn't work - it would be awesome if someone could give me a clue as to why.

loginreq = {"username":username, "password":password, "productType":"CFD_Demo"}
authreq_data = {"req":loginreq}
authreq_data = simplejson.dumps(authreq_data)

A

#The dictionary contains a dictionary
 
M

MRAB

Hi there,

I am attempting to use simplejson.dumps to convert a dictionary to a json encoded string.

For some reason this doesn't work - it would be awesome if someone could give me a clue as to why.

loginreq = {"username":username, "password":password, "productType":"CFD_Demo"}
authreq_data = {"req":loginreq}
authreq_data = simplejson.dumps(authreq_data)

A

#The dictionary contains a dictionary

Which version of Python? Versions of Python since 2.6 come with a
"json" module.
 
C

Chris Rebert

If I print authreq_data to screen  I get

{"req": {"username": "######", "password": "#####", "productType": "CFD_Demo"}}

Essentially I want the inner brackets to be  [ ] instead of {} but alternating on each level so it would be:

{"req": [{"username": "######", "password": "#####", "productType": "CFD_Demo"}]}

as per usual json.

I don't think there's a "usual JSON", but anyway, if you want a list,
then just use one:

from json import dumps
loginreq = {"username":username, "password":password, "productType":"CFD_Demo"}
authreq_data = {"req":[loginreq]} # note brackets
authreq_data = dumps(authreq_data)
{"req": [{"username": "USER", "password": "PASS", "productType": "CFD_Demo"}]}

Cheers,
Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top