Making a list of elements from particular parameters in a JSON file

json array of objects
json list of lists
json array of arrays
complex json example
json multidimensional array
json array of objects java
json multiple objects
json object

I am doing an assignment for school and I am asked to make a list of names of nobel peace prize winners for a particular year and category. This is a sample of the JSON file:

[{
        'year': '2018',
        'category': 'physics',
        'overallMotivation': '"for       groundbreaking inventions in the field of laser physics"',
        'laureates': [{
                'id': '960',
                'firstname': 'Arthur',
                'surname': 'Ashkin',
                'motivation': '"for the optical tweezers and their application to biological systems"',
                'share': '2'
            }, {
                'id': '961',
                'firstname': 'Gérard',
                'surname': 'Mourou',
                'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"',
                'share': '4'
            }, {
                'id': '962',
                'firstname': 'Donna',
                'surname': 'Strickland',
                'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"',
                'share': '4'
            }
        ]
    }, {
        'year': '2018',
        'category': 'chemistry',
        'laureates': [{
                'id': '963',
                'firstname': 'Frances H.',
                'surname': 'Arnold',
                'motivation': '"for the directed evolution of enzymes"',
                'share': '2'
            }, {
                'id': '964',
                'firstname': 'George P.',
                'surname': 'Smith',
                'motivation': '"for the phage display of peptides and antibodies"',
                'share': '4'
            }, {
                'id': '965',
                'firstname': 'Sir Gregory P.',
                'surname': 'Winter',
                'motivation': '"for the phage display of peptides and antibodies"',
                'share': '4'
            }
        ]
    }
]

I am supposed to find a way to find the full names of the people who won for a particular category and year, this is my current code

def get_laureates(dict_prizes, year = "none", category = "none"):


    names = []
    for row in dict_prizes: 
        if row["category"] == category:
            names.append(row["firstname"] + row['surname'])
    return names

year = 2018
category = "peace"

get_laureates(dict_prizes, year = 2018, category = "peace")

and this is the output

    TypeError                                 Traceback (most recent call last)
<ipython-input-168-57a2293c1bca> in <module>
         11 category = "peace"
         12 # test your function here
    ---> 13 get_laureates(dict_prizes, category = "peace")

    <ipython-input-168-57a2293c1bca> in get_laureates(dict_prizes, year,         category)
          4     names = []
          5     for row in dict_prizes:
    ----> 6         if row["category"] == category and row["year"] == year:
          7             names.append(row["firstname"] + row['surname'])
          8     return names

    TypeError: string indices must be integers

I know there are many errors in this code, I've been unable to convert year into integers, even with the removal of the "years" parameter, I am unable to generate a result with just the category. Any help would be greatly appreciated as I am totally clueless when it comes to JSON (The reading material given to me literally just taught me about dump and load).

Your code generally works which means there is something you are missing on your input data that you didn't post here. I could not reproduce the exact error you are seeing with the data you gave us.

There is one issue that you aren't considering -- you need to loop through the laureates as well and then pull out that winner since that is also a list of dictionaries. I did that below:

dict_prizes = [{'year': '2018', 'category': 'physics', 'overallMotivation': '"for       groundbreaking inventions in the field of laser physics"', 'laureates': [{'id': '960', 'firstname': 'Arthur', 'surname': 'Ashkin', 'motivation': '"for the optical tweezers and their application to biological systems"', 'share': '2'}, {'id': '961', 'firstname': 'Gérard', 'surname': 'Mourou', 'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"', 'share': '4'}, {'id': '962', 'firstname': 'Donna', 'surname': 'Strickland', 'motivation': '"for their method of generating high-intensity, ultra-short optical pulses"', 'share': '4'}]}, {'year': '2018', 'category': 'chemistry', 'laureates': [{'id': '963', 'firstname': 'Frances H.', 'surname': 'Arnold', 'motivation': '"for the directed evolution of enzymes"', 'share': '2'}, {'id': '964', 'firstname': 'George P.', 'surname': 'Smith', 'motivation': '"for the phage display of peptides and antibodies"', 'share': '4'}, {'id': '965', 'firstname': 'Sir Gregory P.', 'surname': 'Winter', 'motivation': '"for the phage display of peptides and antibodies"', 'share': '4'}]}]

def get_laureates(dict_prizes, year = "none", category = "none"):
    names = []
    for row in dict_prizes: 
        if row["category"] == category:
            for winner in row['laureates']:   # You need this loop for the inner list of dictionaries
                names.append(winner['firstname'] + winner['surname'])
    return names

year = 2018
category = "physics"

get_laureates(dict_prizes=dict_prizes, year=2018, category=category)

And got:

>>> get_laureates(dict_prizes=dict_prizes, year=2018, category=category)
['ArthurAshkin', 'GérardMourou', 'DonnaStrickland']

Since you are taking in year you'll need to solve for that part as well which I didn't include since you didn't.

JSON Array – REST API Tutorial, JSON array are ordered list of values. JSON array can store multiple value types. JSON array can store string, number, boolean, object or other array inside JSON array. In JSON array Get value at specific index location in array. You can  JSON Uses JavaScript Syntax. Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript. With JavaScript you can create an object and assign data to it, like this:

For the provided data you have a list of JSON objects, each of which comprises of

'year': type (string)
'category': type(string)
'overallMotivation': type(string)
'laureates' : type(list) - > this list comprises of more json objects

Since you need the first and the last name of all the author, you need to traverse through both the list. The initial one first to match the "year" and "category" (to match your year kindly change the data-type of year to string), then traverse through the "laureates" and keep on appending row["firstname"] + row['surname']

def get_laureates(dict_prizes, year = None, category = None):
    names = []
    for category_wise_elements in dict_prizes:
        if category_wise_elements["category"] == category and 
           category_wise_elements['year'] == str(year):
            for winner in category_wise_elements['laureates']:
                names.append(winner["firstname"] + winner['surname'])
    return names

year = 2018
category = "peace"

get_laureates(dict_prizes, year = 2018, category = "peace")

I hope this should help you

JSON Data Set Sample, the JSON DataSet will create a row for each element in the JSON array, and store its <div class="liveSample" spry:region="dsExample3"> Values from object: In this particular example, because we have not specified a "path" constructor In this example, we are simply going to list the types of items in our JSON object. In a JSON file, an object begins with an open curly brace ( {) and ends with a closing brace ( } ). JSON also supports “arrays,” which are ordered lists of values. An array begins with an opening bracket ( [) and ends with a closing one (] ). From these simple definitions, of course, arbitrary complexity can arise.

Here, I just solved your function by using and if that checks that both year and category match the input you are giving them. That way you can search for all values belonging to that specific criteria. Furthermore, year needs to be treated as string when checking for condition because of how it is expressed within the json file. You can obviously delete the else: line which was made only for validation purposes.

def get_laureates(category,year,json):  
    names = []
    for j in range(len(json)):
        if (json[j]['year'] == str(year)) and (json[j]['category'] == category):
            for i in range(len(json[j]['laureates'])):
                names.append(json[j]['laureates'][i]['firstname'] + ' ' + json[j]['laureates'][i]['surname'])
        else:
            print('Not found for category '+category+' and year '+str(year))
    return names
print(get_laureates(category='physics',year=2018,json=json))

Output:

Not found for category physics and year 2018
['Arthur Ashkin', 'Gérard Mourou', 'Donna Strickland']
Super check for consistency

You can add this right after defining the function:

possibilities = ['physics','chemistry']
for i in range(len(possibilities)):
    print(get_laureates(category=possibilities[i],year=2018,json=json))

Output:

Not found for category physics and year 2018
['Arthur Ashkin', 'Gérard Mourou', 'Donna Strickland']
Not found for category chemistry and year 2018
['Frances H. Arnold', 'George P. Smith', 'Sir Gregory P. Winter']

array, In JSON, each element in an array may be of a different type. Language-specific info: Python; Ruby. In Python, "array" is analogous to a list or tuple type,  In this particular project, we have our json files in the assets folder, so we have to load the json in this way. But if you have your json file on the cloud, you can do a network call instead.

A didactic foolproof solution:

def extract_names(list_names):
    # Extraction of fisrtname and surname in "laureates"
    return [
        "{} {}".format(dicc.get('firstname', ''), dicc.get('surname', '')) for dicc in list_names
    ]


def get_nobels(list_data, year='', category=''):
    # We create the condition of identification of year and category:
    bool_condition = lambda _: _.get('year') == str(year) and _.get('category') == str(category)

    # Extraction of the names that meet the condition:
    elements_select = [
        extract_names(dicc.get('laureates', [])) for dicc in list_data if bool_condition(dicc)
    ][0]

    return elements_select


print(get_nobels(list_nobel, 2018, 'chemistry'))

Access and print a specific JSON value, You need to use dot notation and JavaScript to access the JSON values you want​. makes it easy for anybody in your organization to model and document APIs, To pull out the wind speed element from the JSON response and print it to the a specific property, arrays require you to select the position in the list that you  Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

Working with the JSON functions, For example, a bakery makes its product list available to clients in JSON format •JSONGetElement – Queries JSON data for an element (an object, array, or value​) The first parameter of these functions, json, specifies the text field, variable,  how to create JSON file? You Just need to open any text editor paste below code and save that file with .json extension that's it, your JSON file is ready.

Processing JSON data, How can I extract specific data items from a JSON record? Write tabular data from selected elements from a JSON document to a csv file lists and other dictionaries, makes the dictionary object very versatile, you can create The questions themselves have been replaced with unique Keys, the values are the answers. JSON objects are surrounded by curly braces {}. JSON objects are written in key/value pairs. Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null). Keys and values are separated by a colon. Each key/value pair is separated by a comma.

Querying Semi-structured Data, Parsing Text as VARIANT Values Using the PARSE_JSON Function CREATE OR REPLACE TABLE car_sales ( src variant ) AS SELECT PARSE_JSON(​column1) AS src There are two ways to access elements in a JSON object: For example, in the following list, the first two paths are equivalent, but the third is not:. Now let’s talk about how to print output in Json. This can be done by the JsonOutput method. This method is responsible for serialising Groovy objects into JSON strings. Syntax Static string JsonOutput.toJson(datatype obj) Parameters − The parameters can be an object of a datatype – Number, Boolean, character,String, Date, Map, closure etc.

Tutorial: Query a Database and Write the Data to JSON, Then, write data to the JSON file format. Create a New Project On the SQL task, select the Database Server resource from the drop-down list. An open bracket "{" is specified in the element to make it easier to identify the This may be expressed by a combination of constant values and RowSet column references. This code says to find the element with the ID windSpeed and add the content variable after it. Get the value from an array. In the previous section, you retrieved a value from a JSON object. Now let’s get a value from an array. Let’s get the main property from the weather array in the response. Here’s what the JSON array looks like:

Comments
  • Are you sure that your input data matches that as far as the outer part is concerned? The error is that dict_prizes is returning a list, you are iterating that list and returning a string for row which is why row["category"] is causing that error.
  • Why does the json start with a [ bracket and end with a } curly braces? What is the correct format? I can help you work out the function, but need the correct format to begin with.
  • @CeliusStingher it isn't the end of the entire json, that was just part of it! The json itself does end with a ]
  • Gotcha. Working on it
  • I doubt introducing new packages is a good idea if it's homework.