Python JSON – Change separators of JSON data

In this post we will be creating a Python script that will change the separators of existing JSON data, to help us achieve this we will be using the built-in JSON library which allows for easy encoding of Python objects into JSON format as well as the decoding of JSON data into Python objects. It can handle various data types such as lists, dictionaries, strings, and numbers.

See the snippet of Python code below where we change the separators of our JSON data, here we are using the ‘json.dump()’ method used to serialize data to a file-like object in JSON format. This method also has an additional ‘separators’ parameter where we can change them from the default which is (‘,‘ , ‘:‘).

In this example we change our separators to (‘|‘ , ‘@‘).

import json

data = {"Name": "Bobby", "Age": 28, "City": "New York"}

json_data = json.dumps(data, separators=('|' , '@'))

The above would return the following as output.

{"name"@"John"|"age"@30|"city"@"New York"}

See the below output if no separators were to be defined.

{"Name": "Bobby", "Age": 28, "City": "New York"}

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply