Skip to content

Instantly share code, notes, and snippets.

@jpetitcolas
Last active October 21, 2020 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpetitcolas/cd00a3560a2539393f46a63ae5ac8959 to your computer and use it in GitHub Desktop.
Save jpetitcolas/cd00a3560a2539393f46a63ae5ac8959 to your computer and use it in GitHub Desktop.
Pythonise JS JSON dump
/*
Python and Node don't stringify JSON object the same way.
Python adds some spaces after `:` and `,`, causing some trouble if
you try to compute the same hashes across languages.
Here is a Node function turning a Node generated JSON string into
its Python equivalent.
*/
export const pythonizeJsonDump = (jsonDump) =>
jsonDump.replace(/(?!\B"[^"]*)(:|,)(?![^"]*"\B)/g, '$1 ');
/*
pythonizeJsonDump
✓ should turn {"age":23,"lastName":"Doe"} to {"age": 23, "lastName": "Doe"} (157 ms)
✓ should turn {"text":"Hello,world!"} to {"text": "Hello,world!"} (145 ms)
✓ should turn {"text":"Hello:world!"} to {"text": "Hello:world!"} (129 ms)
*/
import pythonizeJsonDump from './pythonizeJsonDump';
describe('pythonizeJsonDump', () => {
it.each`
jsonDump | pythonDump
${'{"age":23,"lastName":"Doe"}'} | ${'{"age": 23, "lastName": "Doe"}'}
${'{"text":"Hello,world!"}'} | ${'{"text": "Hello,world!"}'}
${'{"text":"Hello:world!"}'} | ${'{"text": "Hello:world!"}'}
`('should turn $jsonDump to $pythonDump', ({ jsonDump, pythonDump }) => {
expect(pythonizeJsonDump(jsonDump)).toBe(pythonDump);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment