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.
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!
I have a json object file and at the beginning of this file a header of text, date, time, IP address.
I've tried f.readlines()[5:] to no avail.
I've tried next(f)
I wish to skip 5 or 6 lines of text and go directly into the json data.
Here is an example.
import jsonlines
import json
data_file = input("Enter a file to parse: ")
with jsonlines.open(data_file) as file:
for obj in file:
try:
jsonparse = json.loads(obj)
except Exception as e:
pass
print(obj)
Error:
jsonlines.jsonlines.InvalidLineError: line contains invalid json: Expecting value: line 1 column 1 (char 0) (line 1)
Top of json file:
Start: 07/02/2019 14:59:40.686
Connected To:
192.168.11.203
Here is the full long error:
Enter a file to parse: Play.raw
Traceback (most recent call last):
File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\site-packages\jsonlines\jsonlines.py", line 159, in read
value = self._loads(line)
File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\sdickey\AppData\Local\Programs\Python\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)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:/Users/sdickey/PycharmProjects/Python Testing/Actall Data/testing.py", line 6, in <module>
for obj in file:
File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\site-packages\jsonlines\jsonlines.py", line 204, in iter
skip_empty=skip_empty)
File "C:\Users\sdickey\AppData\Local\Programs\Python\Python37\lib\site-packages\jsonlines\jsonlines.py", line 164, in read
six.raise_from(exc, orig_exc)
File "<string>", line 3, in raise_from
jsonlines.jsonlines.InvalidLineError: line contains invalid json: Expecting value: line 1 column 1 (char 0) (line 1)
Process finished with exit code 1
It is always preferable not to read the whole file in memory but one line at a time.
Assuming your input file contains:
first line
second line
third line
fourth line
fifth line
{ "k1": "val1", "k2": "val2" }
{ "k3": "val3", "k4": "val4" }
if you just want to skip 5 lines, you could do it brutally as:
import json
with open("test.txt") as f:
for _ in range(5):
next(f)
for line in f:
obj = json.loads(line)
print(obj)
or using enumerate:
import json
with open("test.txt") as f:
for i, line in enumerate(f):
if i<5:
continue
obj = json.loads(line)
print(obj)
or use itertools' dropwhile:
import itertools as it
import json
with open("test.txt") as f:
for i, line in it.dropwhile(lambda i: i[0]<5, enumerate(f)):
obj = json.loads(line)
print(obj)
I think you are trying to convert to json line by line. You need to join all lines by \n igoring the first 5 lines and then load it:
import json
with open("test.txt") as f:
json_obj = "\n".join(f.readlines()[5:])
jsonparse = json.loads(json_obj)
print(jsonparse)
I am getting jsondecode error when I am trying trying to print requests.responce.json() after running the post method.
import requests
import requests_ntlm,json
import sharepy
import warnings
warnings.filterwarnings("ignore")
base_url = 'https://company.sharepoint.com'
folderUrl = 'Shared Documents'
headers = {
"Accept":"application/jason; odata=verbose",
"Content-Type":"application/jason; odata=verbose",
"odata": "verbose",
"X-RequestDigest":"true"
}
r1 = sharepy.connect(base_url,username='user#company.onmicrosoft.com',password='password')
filename = 'testupload.mp4'
request_url = base_url + '/_api/web/getFolderByServerRelativeUrl(\'''Shared Documents''\')/Files/add(url=\'' + filename + '\',overwrite=true)'
k = r1.post(url= base_url +"/_api/contextinfo",headers=headers)
print(k.json())
i am getting below error
Traceback (most recent call last):
File "sharepointextended.py", line 28, in <module>
print(json.loads(k.content.decode('utf-8')))
File
"C:\Users\saipr\AppData\Local\Programs\Python\Python37\lib\json\__init__.py",
line 348, in loads
return _default_decoder.decode(s)
File
"C:\Users\saipr\AppData\Local\Programs\Python\Python37\lib\json\decoder.py",
line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File
"C:\Users\saipr\AppData\Local\Programs\Python\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)
Looks like typo in your request headers.
I am assuming the value should be 'application/json' and not 'application/jason'.
Please ignore this answer if this doesnt help as I am new to python. But, I dont think the post call would have been successful in line with general XMLHTTPRequest implementations.
I'M just playing around to the CISCO switch device using netmiko module and having my credentials like IP address, password , user name in a json file and calling that json file into the python script to get these details.. while executing this i'm getting ad error, i have given the details below, please suggest what i'm doing wrong ...
$ cat CiscoNet_6.py
#!/usr/bin/python3
from __future__ import absolute_import, division, print_function
import netmiko
import paramiko
import json
######################################
## JSON: Javascript object Notation ##
######################################
# creating a tuple
netmiko_exceptions = (netmiko.ssh_exception.NetMikoAuthenticationException,
netmiko.ssh_exception.NetMikoTimeoutException)
with open('devices.json') as dev_file:
devices = json.load(dev_file)
for device in devices:
try:
print('-'*79)
print('Net Device Address Is: -->', device['ip'])
#print('Net Device Address Is: -->', device)
connection = netmiko.ConnectHandler(**device)
print(connection.send_command('show clock'))
print('-'*79)
connection.disconnect()
except netmiko_exceptions as e:
#print('Authentication failed to', 'Device')
print('Failed to', device['ip'], e)
#print('Failed to', device, e)
My JSON File devices.json:
[
{
"ip: "192.168.0.200",
"device_type": "cisco_ios",
"username": "nettest",
"password": "cisco123"
}
]
Error:
Traceback (most recent call last):
File "./CiscoNet_6.py", line 18, in <module>
devices = json.load(dev_file)
File "/python/v3.6.1/lib/python3.6/json/__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/python/v3.6.1/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/python/v3.6.1/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/python/v3.6.1/lib/python3.6/json/decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 3 (char 7)
maybe this is why
"ip*"*: "192.168.0.200",
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 ?