i have a json file I am reading in; looks similar to:
[
{
"Destination_IP": "8.8.4.4",
"ID": 0,
"Packet": 105277
},
{
"Destination_IP": "9.9.4.4",
"ID": 0,
"Packet": 105278
}
]
when i parse the json via:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {0} | value: {0}".format(key, value))
I am getting:
key: Destination_IP | value: Destination_IP
I have tried using .items()
and I have tried just iterating over the keys via iterkeys()
and keys()
to no avail.
I can call it direct via json_dict['Destination_IP']
and the value returns.
for json_dict in data:
if 'Destination_IP' in json_dict.keys():
print json_dict['Destination_IP']
returns:
key: Destination_IP | value: 8.8.4.4
I'm on python 2.7, so any help in running down the value portion would be greatly appreciated.
Change your string formats index:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {0} | value: {1}".format(key, value))
Or without using index:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {} | value: {}".format(key, value))
Also you can using names instead of index:
for json_dict in data:
for key,value in json_dict.iteritems():
print("key: {key} | value: {value}".format(key=key, value=value))
Update: In python3.6 and later, f-string feature added that allow programmers to make formatted string easiest, a f-string work same as template engine that starting by f
prefix and string body come after, and variables and other dynamic things must determine between {}
signs, same as below:
print(f'key: A | value: {json_dict["A"]}')
>>> key: A | value: X
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With