0

I have a Python script that updates some value of a JSON file, and the original format of my JSON looks like:

enter image description here

To edit the value I use this code:

 import json

 status_wifi  = "ok" 

 with open("config_wifi.json", "r") as jsonFile:
    data = json.load(jsonFile)
    data['wifi_session']['status'] = status_wifi 

 with open("config_wifi.json", "w") as jsonFile:
  json.dump(data, jsonFile)

But when the values are updated, the format of my JSON is compressed like this:

enter image description here

I want the JSON file to keep its original format with all spaces and line breaks. How could I do that?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
jayen marco
  • 103
  • 2
  • 12

1 Answers1

2

Try json.dumps(json_obj, indent=4)

Example:

import json

status_wifi  = "ok" 

with open("config_wifi.json", "r") as jsonFile:
    data = json.load(jsonFile)
    data['wifi_session']['status'] = status_wifi 

with open("config_wifi.json", "w") as jsonFile:
    json.dump(json.dumps(data, indent=4), jsonFile)

The indent is the number of spaces for a tab. If you set this parameter, the JSON will be formatted.

You can read more about it here.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Dennis Rieke
  • 201
  • 4
  • 18