2

How to filter a json file to show only the information I need?

To start off I want to say I'm fairly new to python and working with JSON so sorry if this question was asked before and I overlooked it.

I have a JSON file that looks like this:

[
    {
        "Store": 417,
        "Item": 10,
        "Name": "Burger",
        "Modifiable": true,
        "Price": 8.90,
        "LastModified": "09/02/2019 21:30:00"
    },
    {
        "Store": 417,
        "Item": 15,
        "Name": "Fries",
        "Modifiable": false,
        "Price": 2.60,
        "LastModified": "10/02/2019 23:00:00"
    }
]

I need to filter this file to only show Item and Price, like

[
    {
        "Item": 10,
        "Price": 8.90
    },
    {
        "Item": 15,
        "Price": 2.60
    }
]

I have a code that looks like this:

# Transform json input to python objects
with open("StorePriceList.json") as input_file:
    input_dict = json.load(input_file)

# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if ] #missing logical test here.

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

# Show json
print(output_json)

What logical test I should be doing here to do that?

3 Answers 3

7

Let's say we can use dict comprehension, then it will be

output_dict = [{k:v for k,v in x.items() if k in ["Item", "Price"]} for x in input_dict]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, exactly what I needed.
1

You can also do it like this :)

>>> [{key: d[key] for key in ['Item', 'Price']} for d in input_dict] # you should rename it to `input_list` rather than `input_dict` :)
[{'Item': 10, 'Price': 8.9}, {'Item': 15, 'Price': 2.6}]

Comments

0
import pprint
with open('data.json', 'r') as f:
        qe = json.load(f)
        list = []
        for item in qe['<your data>']: 
            query = (f'{item["Item"]} {item["Price"]}')

        print("query")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.