Importing json files on GUI using python. getting JSONDecodeError - python

Link to the .json file -> This is the link to the .json file.
I am making a Python based project and what I am trying to do here is to make use of a .json file. However when I tried to import it to use it with the GUI I got the following error.
Thank you in advance.
Traceback (most recent call last):
File "<ipython-input-1-31816de2c4db>", line 1, in <module>
runfile('C:/Users/Akshita/pyex/Webmap/Gui.py', wdir='C:/Users/Akshita/pyex/Webmap')
File "C:\Users\Akshita\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\Akshita\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Akshita/pyex/Webmap/Gui.py", line 12, in <module>
data=json.load(open(r"C:\Users\Akshita\pyex\Webmap\world.json"))
File "C:\Users\Akshita\Anaconda3\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Akshita\Anaconda3\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Akshita\Anaconda3\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Akshita\Anaconda3\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
JSONDecodeError: Expecting value
# -*- coding: utf-8 -*-
"""
Created on Mon May 21 10:15:01 2018
#author: Akshita
"""
from tkinter import *
import json
import difflib
from difflib import get_close_matches
data=json.load(open(r"C:\Users\Akshita\pyex\Webmap\world.json"))
window=Tk()
window.title("Webmap")
l1=Label(window,text="Name_of_place")
l1.grid(row=0,column=0)
val=StringVar()
e=Entry(window,textvariable=val)
e.grid(row=0,column=1)
be=Button(window,text="Enter",command=entry)
be.grid(row=0,column=2)
def entry():
w= e_val.get()
w=w.title()
if w in data:
t.insert("Data matched")
elif len(get_close_matches(w,data.keys(),cutoff=0.8))>0:
t.insert("Did you mean %s instead?" %get_close_matches(w,data.keys())[0])
t=Text(window,height=3,width=20)
t.grid(row=1,column=1)
by=Button(window,text="Yes",command=yeah)
by.grid(row=2,column=1)
def yeah():
t.insert("Processing")
bn=Button(window,text="No",command=nah)
bn.grid(row=2,column=2)
def nah():
t.insert("No such Data")
window.mainloop()

Looks like your JSON file is invalid - the sequence of brackets at the end is incorrect.
The end should look like this:
... <previous data> ... ,[2.96361,36.802216]]]}}]}
You can use online or IDE JSON checkers to validate your file.
update
Got your full json file.
It turns out that it has UTF-8 BOM header. Try to load() it this way:
import json
import codecs
data = json.load(codecs.open('tst.json', 'r', 'utf-8-sig'))
print(data)
Related SO post: https://stackoverflow.com/a/13156715/2315573

Related

I have a problem with json variable setting

i have this code here:
import json
with open("pass_file.txt", "r") as file:
password = json.loads(file.read())
it calls this error:
Traceback (most recent call last):
File "testdoc.py", line 9, in <module>
print(json.loads(file.read()))
File "C:\Program Files\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Program Files\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\Python37\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I dont know why this is happening because i have the same code on another file just with different variable name and file name and it works file. I did notice another similar question about a similar error but it didnt answer my question.
Thanks in advance :)
What is the content of you pass_file.txt ? The python code use json.loads so it expect JSON formated content in the pass_file.txt
For example for a string, the content of this file will be "hello world"
If you don't put quotes, the JSON parsing process will fail.

Parsing a json file in python create difficulties

I want to parse a json file in python. I don't know the content of the file. I downloaded this file from a website in json format.
As per my knowledge to parse a json file we need this code
import json
sourcefile=open("News_Category_Dataset_v2.json","r")
json_data=json.load(sourcefile)
print (json_data)
But I got this error as describe below. jsonparse.py is my file name which is save in my computer d:/algorithm
D:\python\envs\algorithms\python.exe D:/algorithms/jsonparse.py
Traceback (most recent call last):
File "D:/algorithms/jsonparse.py", line 4, in <module>
json_data=json.load(sourcefile)
File "D:\python\envs\algorithms\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "D:\python\envs\algorithms\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "D:\python\envs\algorithms\lib\json\decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 366)
Process finished with exit code 1
How could I fix the problem?
Your file is not json. but it has lines where each one of them is json.
This snippet should help you
import json
json_list = []
for i in open('test.json'):
json_line = json.loads(i)
json_list.append(json_line)
print(json_list)

Not able to import json from commandline for Python

I am currently tring to work with import a json input that is accepted by Python through a commandline argument and I am trying to save the different values to JSON to a list. I am having issues with my code given below and have attached both the code and the error I get below. Any help much appreciated.
import sys
import json
def lookup1 ():
jsonData = json.loads(sys.argv[1])
print jsonData
jsonList = [jsonData['proxy'],jsonData['OS']]
print jsonList
lookup1()
The error is given below:
$ python dynamicMapper.py '{'proxy':1,'OS':2}'
Traceback (most recent call last):
File "dynamicMapper.py", line 9, in <module>
lookup1()
File "dynamicMapper.py", line 4, in lookup1
jsonData = json.loads(sys.argv[1])
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
The commadline argunet that I give is python dynamicMapper.py '{'proxy':1,'OS':2}'
I am not able to find out what is causing this error and if my approach is right.
The script is working fine, you just need to call it the right way:
python dynamicMapper.py '{"proxy":1,"OS":2}'
{u'OS': 2, u'proxy': 1}
[1, 2]
In JSON the strings are quoted with double quotes instead of single quotes. You also need to quote the string passed to script so that shell understands it being a single argument.

Reading the Chrome Bookmarks (JSON) file in Python

I am trying to manipulate the Chrome Bookmarks file in Python, but have fallen at the first hurdle. I have this code:
import json
import os
input_filename = os.getenv("APPDATA") + "\..\Local\Google\Chrome\User Data\Default\history"
with open(input_filename) as data_file:
bookmark_data = json.load(data_file)
When I run this code I get the following error:
Traceback (most recent call last):
File "C:/Users/David/PycharmProjects/MyBookmarks/myBookmarks.py", line 17, in <module>
bookmark_data = json.load(data_file)
File "C:\Python27\lib\json\__init__.py", line 290, in load
**kw)
File "C:\Python27\lib\json\__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "C:\Python27\lib\json\decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python27\lib\json\decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Process finished with exit code 1
I am not that familiar with JSON, but given this is the chrome bookmarks file, I doubt it is a problem with the structure of the file, and I am stumped as to what to try next! Any ideas?
Thanks in advance.
Bookmarks is the name of the JSON file which you want to open
History is a database file which contains information on URL visits
and files downloaded
Specifying the encoding worked for me
with open(input_filename, "r", encoding='utf-8') as data_file:
bookmark_data = json.load(data_file)
Inspiration: https://pypi.org/project/chrome-bookmarks/

Can't read JSON file in Python

I tried to read data from a JSON file, but I encountered weird error and have no idea what it means. I tried googling it, but it didn't help. I got the following error:
Traceback (most recent call last):
File "items_uploader.py", line 40, in <module>
main()
File "items_uploader.py", line 16, in main
LoadItemsData(settings['items_filename'])
File "items_uploader.py", line 36, in LoadItemsData
data = json.load(json_data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 278, in load
**kw)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 8 column 397 (char 3064)
The code itself is quite simple:
import socket
import MySQLdb
from ConfigParser import SafeConfigParser
import json
from pprint import pprint
def main():
settings = GetSettings()
LoadItemsData(settings['items_filename'])
return
def GetSettings():
settings = {}
parser = SafeConfigParser()
parser.read('settings.yaml')
settings['items_filename'] = parser.get('files', 'items_filename')
return settings
def LoadItemsData(filename):
json_data=open(filename)
data = json.load(json_data)
return data
if __name__ == '__main__':
main()
Any help would be appreciated!
Make sure your JSON data is in a valid format, one extra character will mess up the python parser. To test your JSON data go here, make sure you can see it in a correct format.
For example, if I had
JSON_data ='{"c":[{"xy":{"xstart":0,"xend":5,"ystart":1,"yend":5},"names":["D","T","O","H","L","C",],"co":["rgb(0,0,128)"]}],"Values":{"D":["11/30/2012"],"T":["09:44:00"],"O":["5848.40"],"H":["5848.40"],"L":["5847.45"],"C":["5848.40"]}}'
The , after C (here ["D","T","O","H","L","C",]) will show an error. So make sure that your data is in correct format and there are no unnecessary characters.
Hope this helps.

Categories