I have this JSON in a file:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [
"id": "valore"
],
"om_points": "value",
"parameters": [
"id": "valore"
]
}
I wrote this script which prints all of the json text:
json_data=open(file_directory).read()
data = json.loads(json_data)
pprint(data)
How can I parse the file and extract single values?
转载于:https://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file
I think what Ignacio is saying is that your JSON file is incorrect. You have []
when you should have {}
. []
are for lists, {}
are for dictionaries.
Here's how your JSON file should look, your JSON file wouldn't even load for me:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": {
"id": "valore"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}
Then you can use your code:
import json
from pprint import pprint
with open('data.json') as f:
data = json.load(f)
pprint(data)
With data, you can now also find values like so:
data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]
Try those out and see if it starts to make sense.
Your data.json
should look like this:
{
"maps":[
{"id":"blabla","iscategorical":"0"},
{"id":"blabla","iscategorical":"0"}
],
"masks":
{"id":"valore"},
"om_points":"value",
"parameters":
{"id":"valore"}
}
Your code should be:
import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pprint(data)
Note that this only works in Python 2.6 and up, as it depends upon the with
-statement. In Python 2.5 use from __future__ import with_statement
, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon.
You can now also access single values like this:
data["maps"][0]["id"] # will return 'blabla'
data["masks"]["id"] # will return 'valore'
data["om_points"] # will return 'value'
data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
for line in f:
data.append(json.loads(line))
"Ultra JSON" or simply "ujson" can handle having []
in your JSON file input. If you're reading a JSON input file into your program as a list of JSON elements; such as, [{[{}]}, {}, [], etc...]
ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.
You can find ujson in the Python package index and the API is almost identical to Python's built-in json
library.
ujson is also much faster if you're loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.
Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this:
with open('data.json', encoding='utf-8') as data_file:
data = json.loads(data_file.read())
Note: use json.loads
instead of json.load
. In Python 3, json.loads
takes a string parameter. json.load
takes a file-like object parameter. data_file.read()
returns a string object.
if you are in python 3 here is how you can do it
{
"connection1": {
"DSN": "con1",
"UID": "abc",
"PWD": "1234",
"connection_string_python":"test1"
}
,
"connection2": {
"DSN": "con2",
"UID": "def",
"PWD": "1234"
}
}
The code should look like assuming connection.json file looks like above
connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>>test1
# Here you go with modified json file:
# data.json file :
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [{
"id": "valore"
}],
"om_points": "value",
"parameters": [{
"id": "valore"
}]
}
# You can call or print data on console by using below lines
import json
from pprint import pprint
with open('data.json') as data_file:
data_item = json.load(data_file)
pprint(data_item)
print(data_item['parameters'][0]['id'])
#Output :
#pprint(data_item) output as :
{'maps': [{'id': 'blabla', 'iscategorical': '0'},
{'id': 'blabla', 'iscategorical': '0'}],
'masks': [{'id': 'valore'}],
'om_points': 'value',
'parameters': [{'id': 'valore'}]}
#print(data_item['parameters'][0]['id']) output as :
valore
There are two types in this parsing.
From a file, you can use the following
import json
json = json.loads(open('/path/to/file.json').read())
value = json['key']
print json['value']
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python