Python Forum
how to filter two fields in json using python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to filter two fields in json using python (/thread-32907.html)



how to filter two fields in json using python - python_student - Mar-15-2021

Hi
I need some help. I'm trying to filter two fieds in json but its not working. This json is from API and have a lot of pages. In first page its work very weel but when I put this same code in 'While' to get next page, do not work

This is what Im trying to do
results['data'] = [x for x in results['data'] if x['id_employee'] in [14,67] and x['active'] == 'true']
Can someone help and say what Iam doing wrong please


RE: how to filter two fields in json using python - michael1789 - Mar-15-2021

How does it not work? Wrong info or error?

If it were me, I'd break that line up into single actions. Then use print statements to see that all my variables and processes are, and are doing, what I hope.


RE: how to filter two fields in json using python - Larz60+ - Mar-15-2021

It's next to impossible to visualize your problem without viewing your code.
JSON can be read into a python dictionary, modified and either re-written or reprocessed as is.

Here's an example that will read and display the contents of a JSON file.
(Works on fairly complex dictionaries, with or without nesting, but not extensively tested,
Also I tested on Linux, but should work on other platforms)
import json
import tkinter.filedialog as fd


class ViewJSON:
    def __init__(self):
        self.jdict = {}

    def display_dict(self, dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                self.display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1

    def read_jsonfile(self):
        filename = fd.askopenfilename(defaultextension='.json')
        with open(filename) as fp:
            self.jdict = json.load(fp)


def main():
    vj = ViewJSON()
    vj.read_jsonfile()
    vj.display_dict(vj.jdict)


if __name__ == '__main__':
    main()



RE: how to filter two fields in json using python - python_student - Mar-15-2021

I'm not getting an error message. The Task works correctly, but it is not filtering the results I need. Returns empty json, like this

[
[],
[]
]


RE: how to filter two fields in json using python - python_student - Mar-15-2021

My code I posted above. All I want to do is like Where clause with and in SQL.
All employees in (11,22) and active = true.

I don't know the better way to do it in python