Python Forum

Full Version: Reading a json file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I've a file with the following data:
[{"hour": "09", "minutes": "00"}, {"ext_ip": "82.334.188.22"}, {"status": "1"}]
A test code reads the file content and prints out the data type:
import time, json

datajs = '/home/pi/data/data.json'

set_hr = 8 #opening hour
set_min = 0 #opening minute
ext_ip = ''
status = 1 #blinds activated

def read_json():
    global set_hr, set_min, ext_ip, status
    f = open(datajs, 'r')
    data = json.load(f)
    set_hr = int(data[0]['hour'])
    set_min = int(data[0]['minutes'])
    ext_ip = data[1]['ext_ip']
    status = data[2]['status']
    f.close()

read_json()

print('hr type: {} {}'.format(type(set_hr), set_hr))
print('min type: {} {}'.format(type(set_min), set_min))
print('ip type: {} {}'.format(type(ext_ip), str(ext_ip)))
print('status type: {} {}'.format(type(status), status))
and these are the results:
hr type: <class 'int'> 9
min type: <class 'int'> 0
ip type: <class 'str'> 82.213.217.163
status type: <class 'str'> 1
Why the status data is shown as a string when it's an int?
TIA
(Mar-15-2020, 09:10 AM)ebolisa Wrote: [ -> ]Why the status data is shown as a string when it's an int?
from what you show it's a string - it is enclosed in quotes and you don't cast it to int like you do with hour and minutes values

it's interesting why it's a list of dicts, and not single dict (I speak in terms of python objects, not json array/object terms)
Bonkself I new it was some stupid! Thanks.

(Mar-15-2020, 09:15 AM)buran Wrote: [ -> ]it's interesting why it's a list of dicts, and not single dict (I speak in terms of python objects, not json array/object terms)

It's a file generated by a php code.