EcSync
EcSync

Reputation: 860

How can I get and print specific data from a json query?

So i want to be able to pull data based on a certain condition, from this data i then want to be able to print multiple items from this query...here's what ive done so far:

def rec():
    qe = JsonQ(r"C:\ShopFloor\data.json")
    res = qe.at('data').where('Status', '=', 1).get()
    for Process, Shortnum in res:
        print(Process['Process'] + " " + Shortnum['Shortnum'])

rec()

this is from the following json file:

{
    "data": [
        {
            "Shortnum": "34567",
            "Process": "SPA",
            "Status": 1,
            "Start_Time": "2016-12-14 15:54:35",
            "Finish_Time": "2016-12-14 15:56:02"
        },
        {
            "Shortnum": "34567",
            "Process": "Figure",
            "Status": 0,
            "Start_Time": "2016-12-08 15:34:05",
            "Finish_Time": "2016-12-08 15:34:09"
        },

How can I get this to work properly? Ideally I am looking for this kind of response from the print:

SPA 34567

cannot get a current output, i get this error... i realise I am passing too many arguments however i couldn't think of a proper way to do it...

Exception has occurred: ValueError
too many values to unpack (expected 2)
  File "C:\ShopFloor\main.py", line 101, in rec
    for Process, Shortnum in res:
  File "C:\ShopFloor\main.py", line 106, in <module>
    rec()

Upvotes: 0

Views: 627

Answers (1)

ajrwhite
ajrwhite

Reputation: 8458

The typical approach to working with JSON in Python is to load the JSON object as a Python dict:

import json
with open('C:/ShopFloor/data.json', 'r') as f:
    qe = json.load(f)
for item in qe['data']:
    if item['Status'] == 1:
        print(f'{item["Process"]} {item["Shortnum"]}')

Note this uses Python 3's f-strings (be sure to alternate single and double quotes when accessing dictionary values in an f-string). In Python 2, replace last line with:

        print('{} {}'.format(item['Process'], item['Shortnum']))

Upvotes: 3

Related Questions