0

I'm trying to manipulate a JSON file and dump it back out.

Below is the JSON file - Note how there are two dictionaries wrapped together below...:

{"installed":
    {"client_id":"xxx",
    "project_id":"quickstart-1557411376659",
    "auth_uri":"xxx",
    "token_uri":"xxx",
    "auth_provider_x509_cert_url":"xxx",
    "client_secret":"xxx",
    "redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]
    }
}

I'm trying to use the following python code to read in the JSON file manipulate it, and write it back out.

with open('google_sheets_credentials.json', 'r+') as file:
    google_sheets_auth_dict = json.load(file)
    #Manipulate file contents here

with open('google_sheets_credentials.json', 'r+') as file:
    json.dump(google_sheets_auth_dict, file)

This code fails after a couple of runs because multiple dictionaries need to be wrapped in a list to be written out as JSON - like so:

The reasoning behind this requirement is explained here

with open('google_sheets_credentials.json', 'r+') as file:
    json.dump([google_sheets_auth_dict], file)

The problem is that I can't do that in this case because this JSON is ultimately being fed into google sheets' API where it does not expect the JSON to be wrapped in a list.

How might I read this file in, manipulate, and spit it back out in the format expected by google?

Matt
  • 1,368
  • 1
  • 26
  • 54

1 Answers1

1

This example case:

import json

example_json = '''{"installed":
    {"client_id":"xxx",
    "project_id":"quickstart-1557411376659",
    "auth_uri":"xxx",
    "token_uri":"xxx",
    "auth_provider_x509_cert_url":"xxx",
    "client_secret":"xxx",
    "redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]
    }
}'''

google_sheets_auth_dict = json.loads(example_json)

google_sheets_auth_dict['client_id'] = 'yyy'

print(json.dumps(google_sheets_auth_dict))

seems to work fine

I'm guessing that something is going wrong in the #Manipulate file contents here bit, which is not shown. Or, the example JSON does not look like the failure case.

howderek
  • 2,224
  • 14
  • 23