Select to view content in your preferred language

Feature type sort order in REST API using Python

4955
1
06-25-2015 11:53 AM
RandyBurton
MVP Alum

I have been working on an issue with Collector and the dropdown box that changes the feature type.  Although I carefully sort the domain used for feature types, it always seems to get published with a jumbled order.  This can be corrected using the Manage New Features section of AGOL, but this can be tedious and can cause other problems.  My best solution was to update the REST API JSON file.  See discussion here: Feature type sort order in drop-down list

I have since been working on a python script to extract the "types" section of the JSON file, reorder the section and print a text file that can be used in the process.  The following script does that.  I was just wondering if others had worked on this problem and what solutions they came up with.  Any comments on the script are also appreciated (since I'm still learning python).

import json
import collections

# set up input and output files
# input comes from ArcGIS Online REST API JSON file
input_file=open('unordered_types.json', 'r')
output_file=open('ordered_types.json', 'w')

# read 'types' section of input file
# UTF-8 BOM: file starts with \xef\xbb\xbf
# Windows may add BOM, which needs to be removed
result = json.loads(input_file.read().decode("utf-8-sig").encode("utf-8"),
                    object_pairs_hook=collections.OrderedDict)[u'types']

# sort result dictionary by 'id' key
ordered = sorted(result,key=lambda x:x['id'])

# if console output is desired, uncomment next line
# print json.dumps(ordered, indent=4, sort_keys=False)

# convert ordered dictionary back to JSON
back_json=json.dumps(ordered)

# add 'types' to make completed JSON file for REST API
output_file.write('{ "types" : ' + back_json + ' }')

# close output file
output_file.close() 

print 'Done.'
0 Kudos
1 Reply
RandyBurton
MVP Alum

As a short follow up,  I copy the text file created by the python script into jsonlint.com and verify the code.  If it checks out, I will then use it to update my feature with the REST API.