Python Forum

Full Version: first time pyton user - help with json
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello ,
I want to read a json file and get 2 objects form the file (username and IP )
the config.json is :
Output:
{ "IP":"172.16.3.1", "username" : "admin", "password" : "Root", "Remote":"172.16.3.254", "internalNumber":31", "comId":2, }
how do I do this?
this is what I did to read the all file :
import json

with open('/home/pi/Documents/config.json') as json_file:
    data = json.load(json_file)
    print(data)
I have also try to use:
j = json.loads('/home/pi/Documents/config.json')
    print (j['IP'])
but I get error

so what am I missing?


Thanks,
if that's the actual json file - it's not a valid one
look at "internalNumber":31"
it should be "internalNumber":31 or "internalNumber":"31"

and your first snippet would work.

the second one would not work - you need to read the entire file as string and pass it this string to json.loads(), not the filepath
The json file is missing " and has an extra , on the end
Output:
{ "IP":"172.16.3.1", "username" : "admin", "password" : "Root", "Remote": "172.16.3.254", "internalNumber": "31", "comId": 2 }
Works
(May-06-2019, 11:06 AM)Yoriz Wrote: [ -> ]and has an extra , on the end
yep, I missed that
OK - saw and fix the problem
Thanks !