Home > Mobile >  How to edit json files (delete Objects / replace values)?
How to edit json files (delete Objects / replace values)?

Time:04-13

I have a bunch of JSON files (metadata for my nft collection) what I am trying to do :

  • remove dna section from all files
  • remove null values

The process:

  1. read and parse all these files
  2. make edits and write it in the same file
{
  "dna": "xxxxxxxxxxx", #Delete this line from all
  "attributes": [
    {
      "trait_type": "xxxx",
      "max_value": null  # delete null values
    }
  ],
}

CodePudding user response:

hopefully this will point you in the right direction:

import json

d = json.load(fp)
for key in [x for x in d.keys() if x != 'dna' and d[x] != None]:
 value = d[key]
 print(key,value)

CodePudding user response:

Supposing you have loaded your json into nft with

with open('<filename>', 'r') as f:
    nft = json.load(f)

You can delete them using dict.pop(key: Hashable) like so

nft.pop('dna')
if nft.get('attributes'):
    for attrs in nft.get('attributes'):
        keys = []
        for key in attrs:
            if attrs[key] is None:
                # attrs.pop(key)
                keys.append(key)
        for key in keys:
            attrs.pop(key)

print(nft)  # {'attributes': [{'trait_type': 'xxxx'}]}
  • Related