I have this data inside my text.txt:
[{"title": "T", "genre": "G", "director": "D", "year": "R"}]
When I try to load it this way (line 6):
class Movie:
def __init__(self, **new_movie):
movies = []
with open ('movies.txt', 'r') as f:
if f.read() != '':
movies = json.load(f)
if not verify_uniqueness(new_movie, movies):
print('Movie has already been added.')
else:
self.title = new_movie['title']
self.genre = new_movie['genre']
self.director = new_movie['director']
self.year = new_movie['year']
I get the following error:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
How can I read the data?
with open ('movies.txt', 'r') as f:
if f.read() != '':
movies = json.load(f)
Since f is essentially a generator, calling f.read() in the if condition consumes it, and by the time json.load(f) is called f is empty:
with open ('movies.txt') as f:
print(f.read())
# file content
print(f.read())
# ''
You have to store the file's content in a variable and then use json.loads:
with open('movies.txt') as f:
content = f.read()
if content:
movies = json.loads(content)
Related
I'm having an issue in linking Discord.py with JSON. Here's my code:
#client.event
async def on_guild_join(guild):
role = discord.utils.get(guild.roles, name="Muted")
with open("muted_roles.json", "r") as f:
muted_roles = json.load(f)
muted_roles[str(guild.id)] = str(role.id)
with open("muted_roles.json", "w") as f:
json.dump(muted_roles, f, indent=4)
Here's my error:
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\angel\Documents\python\Bots\dave\dave.py", line 59, in on_guild_join
muted_roles = json.load(f)
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\angel\AppData\Local\Programs\Python\Python39\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 thank early for the assistance.
Your JSON file is empty you should fill it with {} and it will fix!
Let say I have a simple dictionary as below:
a = {'animal' : 'fish', 'fruit' : 'apple','vehicle' : 'car'}
I wish to convert a into JSON and write to a file. If I used json.dumps() as below:
b = jason.dumps(a)
with open('output.json', 'w') as f:
f.write(pprint.pformat(b))
The content of the JSON file output.json became:
'{"animal": "fish", "fruit": "apple", "vehicle": "car"}'
What I wish to actually have (in the file) is without quote as below:
{"animal": "fish", "fruit": "apple", "vehicle": "car"}
What is the right way to code it so that I can get the desired output?
Thanks in advance.
[EDIT]: The reason why I need the desired output in file is because I received the error below when I loaded the file.
>>> with open("output.json") as f:
... data = json.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/louis.kok/Analyses/devel/anaconda3/lib/python3.7/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)
Import json library
import json
Save your file properly using json.dump
with open('output.json', 'w') as f:
json.dump(a, f)
Read it using json.load
with open("output.json") as f:
data = json.load(f)
Try this:
with open('task.json', 'w') as f:
s = json.dumps(mydict, indent=2)
f.write('%s\n' % (s))
I'm creating a Discord moderator bot, and I want to create a "custom prefix per server".
My problem is that I'm trying to import json library but it doesn't work. It returns an error.
I'm using the following code (test code)
from discord.ext import commands
import discord
import json
import asyncio
with open("prefixes.json") as json_data:
prefixes = json.load(json_data)
default_prefix = "!"
def prefix(bot, message):
id = message.server.id
return prefixes.get(id, default_prefix)
bot = commands.Bot(command_prefix=prefix)
#bot.command(name="prefix", pass_context=True)
async def _prefix(ctx, new_prefix):
# Do any validations you want to do
prefixes[ctx.message.server.id] = new_prefix
with open("prefixes.json", "w") as f:
json.dump(prefixes, f)
. . .
I get this error from the code above:
===== RESTART: C:\Users\Raphaël\Desktop\Python\Moderator Bot\coreTest.py =====
Traceback (most recent call last):
File "C:\Users\Raphaël\Desktop\Python\Moderator Bot\coreTest.py", line 6, in <module>
prefixes = json.load(json_data)
File "C:\Users\Raphaël\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\Raphaël\AppData\Local\Programs\Python\Python36\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Raphaël\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Raphaël\AppData\Local\Programs\Python\Python36\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 3 column 2 (char 30)
>>>
I found the source of the problem, I forgot a comma.
Now it's working.
I am receiving this error. I am using Python 3.5.0.
Here is my code:
import json
import requests
from tqdm import tqdm
import os.path
r = requests.get("http://prod.ivtr-od.tpg.ch/v1/GetStops.json?key=d95be980-0830-11e5-a039-0002a5d5c51b")
path = "/Users/me/Desktop/JSON/"
pbar = tqdm(r.json()["stops"])
for x in pbar:
tree = {}
fileMON = open(path + x["stopCode"] + ".json", "r", encoding='utf8')
print(fileMON)
if "MON" in json.loads(fileMON()):
tree["MON"] = json.loads(fileMON())["MON"]
and this is the output :
<_io.TextIOWrapper name='/Users/me/Desktop/JSON/31DCdeparts.json' mode='r' encoding='utf8'>
Traceback (most recent call last):
File "json.py", line 14, in <module>
tree["MON"] = json.loads(fileMON())["MON"]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
My JSON file is in the UTF8 encoding. Someone can help me ?
I am trying to write a spider which crawls through the following JSON response:
http://gdata.youtube.com/feeds/api/standardfeeds/UK/most_popular?v=2&alt=json
How would the spider look if I would want to crawl all the titles of the videos? All my Spiders dont work.
from scrapy.spider import BaseSpider
import json
from youtube.items import YoutubeItem
class MySpider(BaseSpider):
name = "youtubecrawler"
allowed_domains = ["gdata.youtube.com"]
start_urls = ['http://www.gdata.youtube.com/feeds/api/standardfeeds/DE/most_popular?v=2&alt=json']
def parse(self, response):
items []
jsonresponse = json.loads(response)
for video in jsonresponse["feed"]["entry"]:
item = YoutubeItem()
print jsonresponse
print video["media$group"]["yt$videoid"]["$t"]
print video["media$group"]["media$description"]["$t"]
item ["title"] = video["title"]["$t"]
print video["author"][0]["name"]["$t"]
print video["category"][1]["term"]
items.append(item)
return items
I always get following error:
2014-01-05 16:55:21+0100 [youtubecrawler] ERROR: Spider error processing <GET http://gdata.youtube.com/feeds/api/standardfeeds/DE/most_popular?v=2&alt=json>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 1201, in mainLoop
self.runUntilCurrent()
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/base.py", line 824, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 382, in callback
self._startRunCallbacks(result)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 490, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 577, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "/home/bxxxx/svn/ba_txxxxx/scrapy/youtube/spiders/test.py", line 15, in parse
jsonresponse = json.loads(response)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
exceptions.TypeError: expected string or buffer
found two issues in your code:
start url is not accessible, I took out the www from it
changed json.loads(response) to json.loads(response.body_as_unicode())
this works well for me:
class MySpider(BaseSpider):
name = "youtubecrawler"
allowed_domains = ["gdata.youtube.com"]
start_urls = ['http://gdata.youtube.com/feeds/api/standardfeeds/DE/most_popular?v=2&alt=json']
def parse(self, response):
items = []
jsonresponse = json.loads(response.body_as_unicode())
for video in jsonresponse["feed"]["entry"]:
item = YoutubeItem()
print video["media$group"]["yt$videoid"]["$t"]
print video["media$group"]["media$description"]["$t"]
item ["title"] = video["title"]["$t"]
print video["author"][0]["name"]["$t"]
print video["category"][1]["term"]
items.append(item)
return items