Search code examples
pythonjsonexecute

Is there a way to make python script execute JSON lookup?


I've tried to find where this may exist but I don't know the right words to search. I have a simple script that I have had to hardcode to lookup function to return each subsequent value but I need to automate it somehow so that I can simply add a value such as 'quantity' and it would respond with the corresponding values. The JSON file I'm using is

[{"_id": {
"$oid": "5968dd23fc13ae04d9000001"},
"product_name": "sildenafil citrate",
"supplier": "Wisozk Inc", "quantity": 261,
"unit_cost": "$10.47"}, 
{"_id": {"$oid": "5968dd23fc13ae04d9000002" }, 
"product_name": "Mountain Juniperus ashei",
"supplier": "Keebler-Hilpert",
"quantity": 292,
"unit_cost": "$8.74"}, 
{ "_id": {
"$oid": "5968dd23fc13ae04d9000003" },
"product_name": "Dextromathorphan HBr",
"supplier": "Schmitt-Weissnat",
"quantity": 211,
"unit_cost": "$20.53"}]

The current Python 2.7 code I made (with stackoverview help) in Spyder that allows me to return the needed values is:

import json
products = open('C:\Users\*location on my computer*\products.json')
readable_json = json.load(products)
for i in readable_json:
print i['_id'], i['product_name'], i['supplier'], i['quantity'], i['unit_cost']

In the end I want to be able to run my script through something along the lines of "python jsonextractor.py ./products.json product_name, unit_cost" producing the values of product_name and unit_cost. Any help or letting me know where to look is appreciated.


Solution

  • You basically need to learn how to read the command line arguments.

    You can refer to the answer here to get some idea: How to read/process command line arguments?