Question

how to remove empty property from a json with python

  • 29 June 2017
  • 3 replies
  • 307 views

Badge +7

Hi,

 

 

I have a json that I'm going to use to update features on an arcgis server.

 

The syntax of my json is:
_result= [{"attributes":{"OBJECTID":objectid, "ATTRIBUTE1": A1 ,  "ATTRIBUTE2": A2 ,  "ATTRIBUTE3": A3,"ATTRIBUTE4": A4, ... ,"ATTRIBUTEN": AN}}]

How can I automatically remove the entries with null values?

 

For the example above, if A2 is NULL or '' then the json should be:

 

_result= [{"attributes":{"OBJECTID":objectid, "ATTRIBUTE1": A1 , "ATTRIBUTE3": A3,"ATTRIBUTE4": A4, ... ,"ATTRIBUTEN": AN}}]

I tried the fillowing code inside a python caller without success.

 

 

def remove_null(feature):
    js = feature.getAttribute('_result')
    for key, value in js.items():
        if value == None or str(value)='':  
            del js[key]
    feature.setAttribute('_result_bis',js)

Thanks


3 replies

Userlevel 2
Badge +17

Hi @arthy, I think you have to load the source JSON document (text string) into a Python data structure before modifying the contents, then dump the result to another JSON document after modifying. You can use the Python json module. e.g.

# PythonCaller Script Example
import json
def remove_null(feature):
    array = json.loads(feature.getAttribute('_result'))
    for m in array:
        m['attributes'] = {k:v for k, v in m['attributes'].items() if v not in (None, '')}
    feature.setAttribute('_result_bis', json.dumps(array))

[Addition] Another implementation example.

# PythonCaller Script Example
import json
def remove_null(feature):
    array = json.loads(feature.getAttribute('_result'))
    for m in array:
        for k, v in m['attributes'].items():
            if v == None or v == '':
                del m['attributes'][k]
    feature.setAttribute('_result_bis', json.dumps(array))
Userlevel 2
Badge +17

Hi @arthy, I think you have to load the source JSON document (text string) into a Python data structure before modifying the contents, then dump the result to another JSON document after modifying. You can use the Python json module. e.g.

# PythonCaller Script Example
import json
def remove_null(feature):
    array = json.loads(feature.getAttribute('_result'))
    for m in array:
        m['attributes'] = {k:v for k, v in m['attributes'].items() if v not in (None, '')}
    feature.setAttribute('_result_bis', json.dumps(array))

[Addition] Another implementation example.

# PythonCaller Script Example
import json
def remove_null(feature):
    array = json.loads(feature.getAttribute('_result'))
    for m in array:
        for k, v in m['attributes'].items():
            if v == None or v == '':
                del m['attributes'][k]
    feature.setAttribute('_result_bis', json.dumps(array))
BTW, why not use the JSONFormatter?

 

0684Q00000ArMLLQA3.png

 

Badge +7

@takashi

 

I use the python caller and it worked perfectly withe the first example of your code above.

 

Reply