The following snippet of code does exactly what you want, but BEWARE that your input (as written in the question) is not a valid json string, you can check here: http://jsonlint.com.

import json

input_json = """
[
    {
        "type": "1",
        "name": "name 1"
    },
    {
        "type": "2",
        "name": "name 2"
    },
    {
        "type": "1",
        "name": "name 3"
    }
]"""

# Transform json input to python objects
input_dict = json.loads(input_json)

# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if x['type'] == '1']

# Transform python object back into json
output_json = json.dumps(output_dict)

# Show json
print output_json
Answer from Joaquin Sargiotto on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-json-data-filtering
Python JSON Data Filtering - GeeksforGeeks
July 23, 2025 - In this example, the below code ... data. It then filters the data by selecting only the "name" and "age" keys, creating a new dictionary called `filtered_data`, and printing the result....
Discussions

How to filter Json File in Python?
Hi, i want to understand and learn, i’ve json files that generate all formats in videos like this 🙂 [ { “format_id”:“sb3”, “format_note”:“storyboard”, “ext”:mhtml”, “protocol”:“mhtml”, “acodec”:“none”, “vcodec”:“none”, “url”:" “width”:48, ... More on discuss.python.org
🌐 discuss.python.org
0
0
October 5, 2022
arrays - Filtering JSON data in python - Stack Overflow
What you've shown is a single JSON array, not a CSV. (File extensions don't matter to Python) Parse the names from the objects in each JSON array row More on stackoverflow.com
🌐 stackoverflow.com
July 4, 2018
How to filter a JSON?
Good day community, Maybe someone could recommend the best way how to filter a JSON output? I’ve made an API request to the server and got a reply: [ { "Id": 111111, "description": [ { "criteria": "Cache", "measurement": null, "comlexName": null, "value": "32MB", "criteriaId": 907, "valueId": ... More on discuss.python.org
🌐 discuss.python.org
0
0
July 6, 2022
How to filter json output from file using python? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
February 10, 2017
🌐
Python.org
discuss.python.org › python help
Is possible to put like condition filter using json - Python Help - Discussions on Python.org
March 23, 2021 - Hello team, I want to understand, is it possible to filter below json data using python. {"logs": [{"filename": "ABC_PARIS_FILE_01.gz", "transmission_start": "23:03:2021 15:21", "transmission_end": "23:03:2021 15:22"}, {"filename": "ABC_INDIA_FILE_02.gz", "transmission_start": "23:03:2021 15:21", "transmission_end": "23:03:2021 15:22"}, {"filename": "ABC_PARIS_FILE_02.gz", "transmission_start": "23:03:2021 15:21", "transmission_end": "23:03:2021 15:22"}, {"filename": "ABC_INDIA_FILE_03.gz", "t...
🌐
Python.org
discuss.python.org › python help
How to filter Json File in Python? - Python Help - Discussions on Python.org
October 5, 2022 - Hi, i want to understand and learn, i’ve json files that generate all formats in videos like this 🙂 [ { “format_id”:“sb3”, “format_note”:“storyboard”, “ext”:mhtml”, “protocol”:“mhtml”, “acodec”:“none”, “vcodec”:“none”, “url”:" “width”:48, ...
🌐
GitHub
gist.github.com › aslamanver › a05e8de98479f617571a97fe3fe48c3c
JSON List Filter in Python · GitHub
JSON List Filter in Python · Raw · json_filter.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Bobby Hadz
bobbyhadz.com › blog › python-filter-json-array
How to filter a JSON array in Python | bobbyhadz
Copied!import json file_name = 'example.json' with open(file_name, 'r', encoding='utf-8') as f: a_list = json.load(f) # 👇️ [{'name': 'Alice', 'salary': 100}, {'name': 'Bobby', 'salary': 50}, {'name': 'Carl', 'salary': 75}] print(a_list) filtered_list = [ dictionary for dictionary in a_list if dictionary['salary'] > 50 ] # 👇️ [{'name': 'Alice', 'salary': 100}, {'name': 'Carl', 'salary': 75}] print(filtered_list) The code sample assumes that you have an example.json file stored in the same directory as your main.py script. ... Copied![ {"name": "Alice", "salary": 100}, {"name": "Bobby", "salary": 50}, {"name": "Carl", "salary": 75} ] ... The json.load() method is used to deserialize a file to a Python object.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
How to filter a JSON? - Python Help - Discussions on Python.org
July 6, 2022 - Good day community, Maybe someone could recommend the best way how to filter a JSON output? I’ve made an API request to the server and got a reply: [ { "Id": 111111, "description": [ { "criteria": "Cache", "measurement": null, "comlexName": null, "value": "32MB", "criteriaId": 907, "valueId": ...
🌐
Like Geeks
likegeeks.com › home › python › 7 ways to filter json array in python
7 Ways To Filter JSON array in Python
In this tutorial, we’ll explore various methods to filter JSON arrays in Python. We’ll learn how to use list comprehension, the filter() function, for loops, Pandas, NumPy, itertools, and JMESPath to filter JSON arrays.
🌐
GeeksforGeeks
geeksforgeeks.org › filtering-json-response-with-python-list-comprehension
Filtering Json Response With Python List Comprehension - GeeksforGeeks
May 10, 2024 - If your JSON response contains nested structures, you can still use list comprehension to filter the data. Here's an example where we filter based on a nested key: This list comprehension filters the JSON response to include only the "city" key from the nested structure.
🌐
jello
kellyjonbrazil.github.io › jello
jello | CLI tool to filter JSON and JSON Lines data with Python syntax. (Similar to jq)
November 29, 2021 - Alternatively, a query file can be specified with -q to load the query from a file. Within the query, _ is the sanitized JSON from STDIN presented as a python dict or list of dicts. If QUERY is omitted then the original JSON input will simply be pretty printed. You can use dot notation or traditional python bracket notation to access key names.
🌐
Linux Hint
linuxhint.com › search_json_python
How to search for data in JSON using python – Linux Hint
The following script will search the entry from books.json file, where the value of the author key is Nikolaos Gkikas using lambda and filter() method. #!/usr/bin/env python3 # Import JSON module import json # Open the existing JSON file for loading into a variable with open('books.json') as ...
Top answer
1 of 1
1

Duplicated code

In order to remove duplicated code, the key is to identify the parts that are identical/different from one place to another. In your case, you could add a filter parameter to your all function (which would then deserve to be named differently).

You could write something like :

def get_result(self, beginFilter=None):
    labels_list = []
    for index in self.result:
        for key, value in index.items():
            if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter)):
                names = value
                labels_list.append(names)
                collection = set(labels_list)
    return collection

def brickyard(self):
    return self.get_result('BYD')

def schoolhouse(self):
    return self.get_result('SCH')

def spa(self):
    return self.get_result('Spa')

As a side-note, I had not given enough thought before writing the code above but if I had to re-do it from the beginning, I'd choose '' as a default value because it wouldn't need a special handling (all strings start with '' as far as I can tell).

Simplifying code

All your name variables were useless. Your names variable is not really useful neither. Also, labels_list could be named labels.

Finally, your conversion from list of labels to set of labels could be done only once at the very end of the function.

def get_result(self, beginFilter=None):
    labels = [] 
    for index in self.result:
        for key, value in index.items():
            if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter)):
                labels.append(value)
    return set(labels) 

Now, it looks clearer that labels could be a set directly instead of converting it afterward.

def get_result(self, beginFilter=None):
    labels = set()
    for index in self.result:
        for key, value in index.items():
            if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter)):
                labels.add(value)
    return labels

You could also write this as a single set comprehension. Set comprehension is a convenient way to define set (you also have list comprehension and dict comprehension and even something called generator expression but this is out of scope at the moment).

It usually goes like this

my_list = [func(x) for x in my_iterable]  # list comprehension
my_set = {func(x) for x in my_iterable}  # set comprehension
my_dict = { my_key(x): my_val(x) for x in my_iterable}  # dict comprehension

In all 3 cases, one could add an optional filtering part so you could write something like:

my_set = {func(x) for x in my_iterable if some_property(x)}

Finally, you can also add more nested iterations. In your case, we could write (but some people would consider that this is going too far):

def get_result(self, beginFilter=None):
    return { value
        for index in self.result
        for key, value in index.items()
        if 'accountLabelType' in key and (beginFilter is None or value.startswith(beginFilter))}

Back to where we came from

Now that I understand better the point of your code, we can try to clean up the get_result function. The filtering can actually be moved out of the function.

def all(self):
    return { value
        for index in self.result
        for key, value in index.items()
        if 'accountLabelType' in key}

def brickyard(self):
    return {v for v in self.all() if v.startswith('BYD')}

def schoolhouse(self):
    return {v for v in self.all() if v.startswith('SCH')}

def spa(self):
    return {v for v in self.all() if v.startswith('Spa')}

or with a helper function :

def all(self):
    return { value
        for index in self.result
        for key, value in index.items()
        if 'accountLabelType' in key}

def filter(self, begin):
    return {v for v in self.all() if v.startwith(begin)}

def brickyard(self):
    return self.filter('BYD')

def schoolhouse(self):
    return self.filter('SCH')

def spa(self):
    return self.filter('Spa')

More

In order not to call all multiple times, one could imagine saving the result.

🌐
DevGenius
blog.devgenius.io › python-or-filtering-in-queries-sorting-json-responses-from-an-oracle-database-95cbf023153a
Python or Filtering in Queries: sorting JSON responses from an Oracle Database | by Chris Hoina | Dev Genius
May 23, 2022 - However, after a recent discussion and a suggestion from thatjeffsmith, I think I should share another way you can sort this data from the source. If you recall, the portion of my python code that: ... def city_choices_python(): import requests import json city_list = [] URL = 'https://gf641ea24ecc468-dbmcdeebyface.adb.us-ashburn-1.oraclecloudapps.com/ords/pythondev/cities/' response = requests.get(URL) r = json.loads(response.text) for nestedArr in r['items']: city_list.append(nestedArr['city']) return sorted(city_list)
🌐
Stack Overflow
stackoverflow.com › questions › 58505054 › filter-out-data-in-json
python 3.x - Filter Out Data in Json - Stack Overflow
import json data = json.loads(... = data1 ... Just load the json file into memory, then use a list comprehension to filter for where the flag is true....
🌐
Stack Overflow
stackoverflow.com › questions › 61870289 › how-to-read-json-data-and-filter-it-from-a-dataframe-where-one-column-has-json-d
python - How to read json data and filter it from a dataframe where one column has json data type - Stack Overflow
-- Python Pandas code import sqlite3 import pandas as pd -- Creating connection cnx = sqlite3.connect('testdatabase.db') Customer = pd.read_sql_query("SELECT * FROM Customer", cnx) Account = pd.read_sql_query("SELECT * FROM Account", cnx) I want to fetch all state names and total of account balance for the users belonging to those states. My expected output would be the following table: ... data = cnx.execute("SELECT JSON_VALUE(c.address, '$.state') AS State, SUM(a.account_balance) AS Account_balance FROM Customer c INNER JOIN Account a ON c.id = a.user_id WHERE JSON_VALUE(c.address, '$.state') IS NOT NULL GROUP BY JSON_VALUE(c.address, '$.state')") for row in data: print "State = ", row[0] print "Account_balance = ", row[1], "\n" cnx.close()
🌐
IT trip
en.ittrip.xyz › python
The Art of Filtering JSON Data in Python: A Step-by-Step Guide | IT trip
November 4, 2023 - When working with large JSON files, you may need to process and filter data in chunks or stream the data to avoid memory issues. Python’s `json` module can decode JSON from an iterable of strings, which means you can process a large JSON file in chunks.