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 need to give list of objects to <code>sorted</code> and <code>key</code> should be method to get value for single object.</p>

<pre><code>In [1]: ll = {"employees": [{"name": "abc"}, {"name": "bcd"}]}

In [2]: sorted(ll['employees'], key=lambda x: x['name'])
Out[2]: [{'name': 'abc'}, {'name': 'bcd'}]
</code></pre>

<p>As you can see I get list of employees to <code>sorted</code>. Then <code>sorted</code> run <code>lambda</code> on every element of that list (so it calls <code>x['name']</code> on <code>{"name": "abc"}</code> and gets <code>name</code>. Then <code>sorted</code> sort elements in list using key (it doesn't matter if it's string or number - string are also numbers somehow - ascii).</p>

<p>When you have sorted list you can assign it to <code>ll['employees']</code> or any other place.</p>

<p>Anyway, guessing your code (cause you didn't include all of it) I assume that you're calling <code>sorted</code> on <code>dict</code>, not <code>list</code>. Also you're using wrong <code>key</code> (<code>k</code> is not full object, but single element in <code>list</code> passed to sorted).</p>

python json