简体   繁体   中英

Incorrect python dictionary to JSON conversion

I'm trying to convert a python dictionary to the target JSON object below. I figured I'd use json.dumps() (as per this thread ) but the result is not the same nevertheless. The target has some unconvential spacing in it, but I'm not allowed to change it or edit them out.

Any idea how to approach this?

import json

dict= {"token":{"name":"John Doe","code":"123456789"}}
target = '{ "token":{ "name":"John Doe", "code":"123456789" } }'

print(json.dumps(dict))
print(json.loads(json.dumps(dict)))
print(target)

>>>{"token": {"name": "John Doe", "code": "123456789"}}
>>>{'token': {'name': 'John Doe', 'code': '123456789'}}
>>>{ "token":{ "name":"John Doe", "code":"123456789" } }

For additional context, I'm trying to prepare the argument passed through Bambora's payment API . See the cURL example associated to this here .

Since you're comparing strings, you'll get a False result if even one space is different between the two strings. This can happen even if the two structures are actually the same in terms of their structure and data. What you really want to do is find a way to remove non-substantive formatting issues from the equation.

Here's how to fix your code to take away the problem of differences in spacing and other non-substantive differences:

import json

dict= {"token":{"name":"John Doe","code":"123456789"}}
target = json.dumps(json.loads('{ "token":{ "name":"John Doe", "code":"123456789" } }'))

print(target == json.dumps(dict))

Result:

True

There are some unnecessary whitespaces in your target JSON.

target = '{ "token":{ "name":"John Doe", "code":"123456789" } }'

You can use the separators argument to get a space after the comma separators.

json.dumps(dict, separators=(', ', ':'))

In order to get the spaces around the curly braces, I am afraid, you will need to use a regular expression based substitution.

json.dumps() returns {"token": {"name": "John Doe", "code": "123456789"}}'

It has no spaces at end of each brackets { and } , but your one string has.

This code returns True :

json.dumps(dict) == '{"token": {"name": "John Doe", "code": "123456789"}}'

Let's take a closer look "white spaces".

The differences are: (your vs. json.dumps)

  • "code:"123" vs. "code": "123"
  • { "token"... vs. {"token"...
  • "token":{ "name"... vs. "token": {"name":..

OR, you could compare two value with no spaces as like:

json.dumps(dict).replace(' ', '') == target.replace(' ', '')

It returns True as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM