如何JSON转储多个字典而不将它们包装在lis中

2024-03-29 07:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试操作一个JSON文件并将其转储回来。你知道吗

下面是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"]
    }
}

我正在尝试使用下面的python代码读入JSON文件并对其进行操作,然后将其写出来。你知道吗

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)

这段代码在运行了几次之后就失败了,因为需要将多个字典包装在一个列表中,然后以JSON的形式写出,如下所示:

这一要求背后的原因解释如下here

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

问题是,在这种情况下我不能这样做,因为这个JSON最终会被输入到googlesheets的API中,它不希望JSON被包装在一个列表中。你知道吗

我该如何读入、操作这个文件,并以google所期望的格式将其吐出呢?你知道吗


Tags: 文件clientauthjson字典aswithgoogle
1条回答
网友
1楼 · 发布于 2024-03-29 07:24:47

此示例案例:

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

我猜#Manipulate file contents here位出错了,但没有显示。或者,示例JSON看起来不像失败案例。你知道吗

相关问题 更多 >