I'm new to working with JSON in python3 and have run into an issue that I couldn't find on SO or google anywhere.I have a program that reads in a JSON file that is formulated as such:
[
{
"message": {
"Y": "15",
"datetime": "2016-05-31 09:00:00",
"X": "174",
"proxCard": "vlagos001",
"type": "mobile-prox",
"floor": "1"
},
"offset": 32400.0
},
{
"message": {
"Y": "15",
"datetime": "2016-05-31 09:00:00",
"X": "174",
"proxCard": "vlagos001",
"type": "mobile-prox",
"floor": "1"
},
"offset": 32400.0
},
.
.
etc
]
My program reads in the file, calls json.load()
on it, and then attempts to go through each item and grab certain variables and later operate on them. However I am having a tough time working with the file and ran into something that I don't understand when checking the types of each var.
The following code is used to get each type of item.
input = open(file)
data = json.load(input)
print(type(data)) #returns <class 'list'>
for obj in data:
print(type(obj)) #returns <class 'dict'>
print(obj)
for key in obj:
print(type(key)) #returns <class 'str'>
print(key)
break
Run through once, the above code returns:
<class 'list'>
<class 'dict'>
{'offset': 32400.0, 'message': {'floor': '1', 'type': 'mobile-prox', 'datetime': '2016-05-31 09:00:00', 'X': '174', 'proxCard': 'vlagos001', 'Y': '15'}}
<class 'str'>
offset
<class 'str'>
message
As you can see, the data
var is a list of dicts
. But when I try to grab the key and value pairs from each object like so:
for obj in data:
print(type(obj)) #returns <class 'dict'>
print(obj)
for key, val in obj:
print(type(key))
print(type(val))
print(key)
print(val)
break
I get an error saying it cant unpack the values, as if it weren't a dict:
<class 'list'>
<class 'dict'>
{'message': {'type': 'mobile-prox', 'proxCard': 'vlagos001', 'X': '174', 'floor': '1', 'datetime': '2016-05-31 09:00:00', 'Y': '15'}, 'offset': 32400.0}
Traceback (most recent call last):
File "data_analysis.py", line 89, in <module>
main()
File "data_analysis.py", line 82, in main
AnalyzeMobileProx(data)
File "data_analysis.py", line 17, in AnalyzeMobileProx
for key, val in obj:
ValueError: too many values to unpack (expected 2)
Could anyone explain why this is? From my understanding, each object is seen as a dict and should have a key, val
pair, one key being "message" and one being "offset", with "message" being a dict on its own in which I can access the values. Any help is appreciated!