sorting json file using python having value as string
<p>i have json file:</p>

<pre><code>ll = {"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"James", "lastName":"Bond"},
    {"firstName":"Celestial", "lastName":"Systems"},
    {"firstName":"Peter", "lastName":"Jones"}
]}
</code></pre>

<p>i want to sort by key(lastname or firstname)</p>

<p>i know the sorting method that we use with number as value but i am not able to sort this by value as string.</p>

<p>i tried below:</p>

<pre><code>#data = json.load(file)
new = sorted(data, key = lambda k: k['employees'].get('lastName',0))
</code></pre>

<p>and getting error:</p>

<pre><code>TypeError: string indices must be integers
</code></pre>

<p>You can sort the <code>ll["employees"]</code> list in-place using the <code>list.sort</code> method. And while you can roll your own key function using <code>lambda</code> it's cleaner and  more efficient to use <code>operator.itemgetter</code>.</p>

<p>In this code, my key function creates a tuple of the <code>lastName</code> followed by the <code>firstName</code>, so the list is primarily sorted by <code>lastName</code>, but people with the same <code>lastName</code> are sorted by <code>firstName</code>.</p>

<pre><code>from operator import itemgetter
from pprint import pprint

ll = {"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Patti", "lastName":"Smith"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"James", "lastName":"Bond"},
    {"firstName":"Celestial", "lastName":"Systems"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

ll["employees"].sort(key=itemgetter("lastName", "firstName"))
pprint(ll)
</code></pre>

<p><strong>output</strong></p>

<pre><code>{'employees': [{'firstName': 'James', 'lastName': 'Bond'},
               {'firstName': 'John', 'lastName': 'Doe'},
               {'firstName': 'Peter', 'lastName': 'Jones'},
               {'firstName': 'Anna', 'lastName': 'Smith'},
               {'firstName': 'Patti', 'lastName': 'Smith'},
               {'firstName': 'Celestial', 'lastName': 'Systems'}]}
</code></pre>

python json