Max Vallee
Max Vallee

Reputation: 468

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.

Upvotes: 0

Views: 1077

Answers (3)

Muntasir Wahed
Muntasir Wahed

Reputation: 297

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.

Upvotes: 1

Joona Yoon
Joona Yoon

Reputation: 324

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.

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23079

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

Upvotes: 1

Related Questions