简体   繁体   English

如何将 ID 从 JSON object 外部移动到内部?

[英]How to move ID from outside JSON object to inside?

I'm trying to create a telegram bot for my fantasy football league, but I hit a small snag.我正在尝试为我的梦幻足球联赛创建一个电报机器人,但我遇到了一个小障碍。 I'm pulling a JSON file that I want to upload to my MongoDB.我正在拉一个 JSON 文件,我想将它上传到我的 MongoDB。 The JSON file has the id on the outside of the object: JSON 文件的 id 在 object 的外部:

{
    "2103": {
        "years_exp": 1,
        "search_rank": 9999999
}

but to be able to pull data from the different collections I have, I would need the id to be on the inside like this:但为了能够从我拥有的不同 collections 中提取数据,我需要将 id 放在内部,如下所示:

{
     {
        "_id": 2103
        "years_exp": 1,
        "search_rank": 9999999
}

I've been trying to parse the file with a dictionary, array, lists and update the JSON file, but I can't figure it out.我一直在尝试使用字典、数组、列表解析文件并更新 JSON 文件,但我无法弄清楚。

Is there a way to convert one format to another?有没有办法将一种格式转换为另一种格式?

 # Given: data = {'2103': {'years_exp': 1, 'search_rank': 9999999}} # List comprehension: # Formats the key as a dictionary and converts it to an integer, # Combines this new dict with the inner value dict. data = [{'_id':int(key)}|value for key, value in data.items()] print(data)

Output (Formatted pretty): Output(格式化漂亮):

 [ { '_id': 2103, 'years_exp': 1, 'search_rank': 9999999 } ]

I hope you find this helpful:我希望这个对你有用:

 let data = {'2103': {'years_exp': 1, 'search_rank': 9999999}} let key = Object.keys(data)[0] let newObj = data[key] newObj._id = key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM