Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
924 views
in Technique[技术] by (71.8m points)

python - Remove all keys that have values of N/A, -, or empty strings

import json

def clean_data():
  r = requests.get('https://coderbyte.com/api/challenges/json/json-cleaning')
  return r.json()

print(clean_data())

Example Input

{"name":{"first":"Daniel","middle":"N/A","last":"Smith"},"age":45}

Example Output

{"name":{"first":"Daniel","last":"Smith"},"age":45}
question from:https://stackoverflow.com/questions/66062074/remove-all-keys-that-have-values-of-n-a-or-empty-strings

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can recursively solve this

import json
import requests


r = requests.get('https://coderbyte.com/api/challenges/json/json-cleaning')
data = r.json()

def clean_data(data):
    if(isinstance(data, dict)):
        to_be_deleted = []
        for k in data:
            if(isinstance(data[k], dict)):
                new_val = clean_data(data[k])
                data[k] = new_val
                
            if(isinstance(data[k], list)):
                new_val = clean_data(data[k])
                data[k] = new_val
                
            elif(isinstance(data[k], str)):
                if(data[k] == 'N/A'):
                    to_be_deleted.append(k)
                    
        for i in to_be_deleted:
            del data[i]
        return data
            
    if(isinstance(data, list)):
        to_be_deleted = []
        for i in range(len(data)):
            if(isinstance(data[i], dict)):
                new_val = clean_data(data[i])
                data[i] = new_val
                
            if(isinstance(data[i], list)):
                new_val = clean_data(data[k])
                data[i] = new_val
                
            elif(isinstance(data[i], str)):
                if(data[i] == 'N/A'):
                    to_be_deleted.append(i)
        for i in to_be_deleted:
            del data[i]
        return data
    
clean_data(data)
data = data = {"name":{"first":"Daniel","middle":"N/A","last":"Smith", "haha": {'hihi':1, "hoho":"N/A"}},"age":45, "hehe":[1,2,3,4,"N/A"]}
clean_data(data)
# {'name': {'first': 'Daniel', 'last': 'Smith', 'haha': {'hihi': 1}}, 'age': 45, 'hehe': [1, 2, 3, 4]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...