Home > Blockchain >  find and replace element in file using python 3.7
find and replace element in file using python 3.7

Time:02-03

I am learning python and in the code below I am trying to replace all values where "id": null, with "id": na,... there may not always be an id in every block. If c does not have that pattern in it then it is skipped. Thank you :)

file

{
 "objects": [
    {
        "version": "1",
        "id": null,
        "date": 1,
         ...,
    },
    {
        "version": "1",
        "id": 1xx1,
        "date": 1,
         ...,
    },

desired

{
"objects": [
    {
        "version": "1",
        "id": na,
        "date": 1,
         ...,
    },
    {
        "version": "1",
        "id": 1xx1,
        "date": 1,
         ...,
    },

python3

import json

with open('file.json',encoding='utf8') as in_file:
data = json.load(in_file)

for c in data['objects']:      # read all elements in object into c
if c = "\"id\""\: null,:       # check to see if element in c is "id": null,
    data[c] = "\"id\""\: na,   # replace c with

CodePudding user response:

The Error is in following code

if c = "\"id\""\: null,:       # check to see if element in c is "id": null,
    data[c] = "\"id\""\: na,   # replace c with

As @Dan-Dev mentioned, the null in c#, c , etc. is None in Python. You can use this code and read my code as side information to understand more.

import json

with open('file.json', 'r') as file:
    data = json.load(file)

for obj in data['objects']:
    if obj.get('id') is None:
        obj['id'] = 'na'
        # if you want to write back
with open('data.json', 'w') as file:

    json.dump(data, file, indent=2)

CodePudding user response:

You want to use None in python for a NoneType not null i.e. if not obj['id']: but None is falsy so you can just use if not

import json


with open('file.json', encoding='utf8') as in_file:
    data = json.load(in_file)
for obj in data['objects']:
    if not obj['id']:
        obj['id'] = 'na'
print(data)

"id": an is invalid as Json and in a Python dictionary I think you want to either initialise an as a variable or use a string "id": "an"

Or more concisely use comprehensions:

import json


with open('file.json', encoding='utf8') as in_file:
    print(json.dumps({'objects': [{k: 'na' if k == 'id' and not v else v for k, v in entry.items()} for entry in json.load(in_file)['objects']]}))
    

As @Mohamed Fathallah suggests use json.dump() to write the data to a file or json.dumps() to display it as a json formatted string.

  • Related