Home > OS >  How to move ID from outside JSON object to inside?
How to move ID from outside JSON object to inside?

Time:07-24

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. The JSON file has the id on the outside of the 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:

{
     {
        "_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.

Is there a way to convert one format to another?

CodePudding user response:

# 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):

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

CodePudding user response:

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
  • Related