Python Forum

Full Version: Sort data from JSON file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there! Have the following task:

***
data.json - file with data about ancient mathematicians.
1. Write function, which reads data from the file. Function parameter is the name of the file.
2. Write function which sorts data by surname in the field 'name' (for those who have it).
For example, in case of Rene Descartes surname is Descartes, for Pierre de Fermat it is Fermat etc.
If there is no surname, use name, for example Euclid.
***

It seems I've coped with the first part, but a bit confused by the second task. As the field name can contain only name, a name and surname, or a name, such word as "de" and surname. But we need to sort data by surname only. Not sure how to code it. Here's what I've done so far:

import json
def read_json(data):
    with open(data, "r", encoding='utf-8') as file:
        result = json.load(file)
    return result

def sort_by_surname(data):
    surname = 
# suppose here I should convert "name" field to a string, then use split to separate words, and make it use the latter word in case there are 2 or 3 words - sounds a bit complicated for me. Is there another way? Or is my version correct. Would be great if you could help me **huh** 
    sort_surname = sorted(data, key=abs(surname))
    print(sort_surname)
Pls help Huh Thanks in advance!
Unless you have a "Surname" field, you're going to have to extract it from name, and that's annoying in edge cases. The final "word" seems to be quite reasonable as a first pass.

Not sure what you're doing with abs there in the key. That's not valid on strings.
What is result?
result = json.load(file)
result is what you have to sort, and sorting requires you know about the things in result. What things do you have in result?

Sounds like you will have to write a function that knows how to get the surname from any object in result. Something like:
def surname(obj):
    if (value := obj.get('surname', None) is not None:
        return value

    if (value := obj.get('full name', None) is not None:
        return value.split(',')[0].strip()

    return ''

sorted_data = sorted(data, key=surname)