Reputation: 765
I have a log file in such format,
{
"box1" : {
"item1" : "testValue1",
"item2" : "testValue2"
},
"foods" : [
{
"orange" : "per pound",
"price" : 2.99
},
{
"rice" : "in bag",
"price" : 1.99
"extra-key" : "extra-Value",
"extra-key2" : "extra-Value2",
},
{
"beer" : "in box",
"price" : 12.99
"extra-key3" : "extra-Value3"
"content" : None
}
]
}
and I want to extract following values into an output file in python:
[ "orange" : "per pound", "rice" : "in bag","beer" : "in box" ]
Can someone show me how it can be done ?
Upvotes: 0
Views: 883
Reputation: 1832
For reading json files, you can use a Python module - json. It reads a file and returns a corresponding data structure stored in a file.
Since you have a dictionary, you can easily access values simply by indexing the dictionary.
import json
with open('logFileName') as f:
data = json.load(f)
# Foods is a list of dictionaries, so you have to access it like that
print data['foods'][0]['orange']
Note that you have incorrectly specified the desired output format because you're mixing list and dictionary syntax. I assume that you, in fact, wanted to extract a dictionary out of the log.
This is a problem if you don't know in advance what type of food will be in a list because it's not easy to determine which key in a dictionary is food (e.g. rice
), and which is something completely different, for example extra-key
.
For a quick introduction to Python, read The Python Tutorial.
Upvotes: 1