Python - ValueError: Expecting value: line 1 column 1 (char 0) - python

This produces and error:
ValueError: Expecting value: line 1 column 1 (char 0)
Here is my code:
...
print("Your phonebook contains the following entries:")
for name, number in phoneBook.items():
print("%s - %s" % (name, number))
while not created:
if not os.path.isfile('phonebook.json'):
with open('phonebook.json', 'wb') as f:
try:
f.write('{}')
except TypeError:
{}
created = True
print('New phonebook created!')
else:
print('Phonebook found!')
created = True
with open('phonebook.json', 'r') as f:
try:
phoneBook_Ori = json.load(f)
phoneBook_Upd = dict(phoneBook_Ori.items() + phoneBook.items())
phoneBook_Ori.write(phoneBook_Upd)
except EOFError:
{}
if EOFError:
with open('phonebook.json', 'w') as f:
json.dump(phoneBook, f)
else:
with open('phonebook.json', 'w') as f:
json.dump(phoneBook_Ori, f)
Has anyone got an idea of how to fix this?
I have also previously asked a question on this code here

I copy pasted your code in the python 2.x interpreter.
I received a ValueError regarding the phonebook.json file. I created a dummy file with:
{'sean':'310'}
My error reads:
ValueError: Expecting property name: line 1 column 2
This was the only way I was able to receive a ValueError.
Therefore, I believe your issue lies in the way the json is written in phonebook.json. Can you post its contents or a subset?
Also, using phoneBook_Ori.write() seems very questionable, as the json module has no method called write(), and the return on json.load(), if used on json objects, is a dictionary, which also cannot write(). You would probably want to use json.dump().
read more at:
https://docs.python.org/2/library/json.html
Anyway, I hope I was helpful.

I was getting this error whilst using json.load(var) with var containing an empty JSON response from a REST API call.
In your case, the JSON response (phonebook.json) must have records. This will fix the error.

Related

Error handling for bad values in JSON loading

I have a problem for loading JSON file using json.load.
with open(file) as json_file:
self._metdata = json.load(json_file)
one the rows in the file is bad and gives this error:
Expecting property name enclosed in double quotes: line 515716 column 1 (char 24223047)
What I want it the json.load to ignore this value and keep loading the rest but I could not find a way to do it.
What I finally did is to read line by line and to check for error but its very slow.
Is there a better way to do it?
Thanks.
for file in [self._metadata_file_name, self._pharses_map_file_name]:
with open(file) as json_file:
for line in json_file:
try:
row = json.loads(line)
if row:
if file == self._metadata_file_name:
self._metdata = {**self._metdata, **row}
else:
self._pharses_map = {**self._pharses_map, **row}
except Exception as e:
self._logger.log(message="Error pasring JSON " + line + ", for model: " + self._mode + ", file: " + self._metadata_file_name, error=str(e), metadata={"mode" : self._mode}, logType=self._logger.LOG_TYPE_ERROR)
You can use json.load for loading a file. At line 515716, add double quote wrap the key. Hope to help you

JSON files parsing error while trying to print certain values using Python (json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 20))

I am new to Python, and I want to convert a JSON file and print it to the console. When I try to print the whole JSON it is throwing
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 20)
My code:
import json
with open('venv/Vt.json', 'r') as json_file:
parsed_json = json.load(json_file)
for idd in parsed_json:
print(idd['t_id'])
My JSON file:
{"index":{"_id":0}}
{"t_id":0,"timestamp":"2016-06-01T09:23:39Z","stat":"571","mod":"M02"}
{"index":{"_id":1}}
{"t_id":0,"timestamp":"2016-06-01T09:23:39Z","stat":"571","mod":"M02"}
While you wait for a better answer, this code (while not great) solves your issue:
with open('venv/Vt.json', 'r') as json_file:
try:
t_ids = [json.loads(line)['t_id'] for line in json_file.readlines()]
print(t_ids)
except Exception:
pass

Iterating through JSON is requiring more for loops than I'd like

I am reading through a .json file and parsing some of the data to save into an Object. There are only 2000 or so items within the JSON that I need to iterate over, but the script I currently have running takes a lot longer than I'd like.
data_file = 'v1/data/data.json'
user = User.objects.get(username='lsv')
format = Format(format='Limited')
format.save()
lost_cards = []
lost_cards_file = 'v1/data/LostCards.txt'
with open(data_file) as file:
data = json.load(file)
for item in data:
if item['model'] == 'cards.cardmodel':
if len(Card.objects.filter(name=item['fields']['name'])) == 0:
print(f"card not found: {item['fields']['name']}")
lost_cards.append(item['fields']['name'])
try:
Rating(
card=Card.objects.get(name=item['fields']['name'], set__code=item['fields']['set']),
rating=item['fields']['rating'],
reason=item['fields']['reason'],
format=format,
rator=user
).save()
except Exception as e:
print(e, item['fields']['name'], item['fields']['set'])
break
with open(lost_cards_file, 'w') as file:
file.write(str(lost_cards))
The code is working as expected, but it's taking a lot longer than I'd like. I'm hoping there is a built-in JSON or iterator function that could accelerate this process.
There is. It's called the json module.
with open(data_file, 'r') as input_file:
dictionary_from_json = json.load(input_file)
should do it.

Tweets streamed using tweepy, reading json file in python

I streamed tweets using the following code
class CustomStreamListener(tweepy.StreamListener):
def on_data(self, data):
try:
with open('brasil.json', 'a') as f:
f.write(data)
return True
except BaseException as e:
print("Error on_data: %s" % str(e))
return True
Now I have a json file (brasil.json). I want to open it on python to do sentiment analysis but I can't find a way. I managed to open the first tweet using this:
with open('brasil.json') as f:
for line in f:
tweets.append(json.loads(line))
but it doesn't read all the other tweets. Any idea?
From comments: after examining the contents of the json data-file, all the tweets are in the odd number if rows. The even numbers are blank.
This caused a json.decoder.JSONDecodeError.
There are two ways to handle this error, either read only the odd rows or use exception-handling.
using odd rows:
with open('brasil.json') as f:
for n, line in enumerate(f, 1):
if n % 2 == 1: # this line is in an odd-numbered row
tweets.append(json.loads(line))
exception-handling:
with open('brasil.json', 'r') as f:
for line in f:
try:
tweets.append(json.loads(line))
except json.decoder.JSONDecodeError:
pass # skip this line
try and see which one works best.

Python inserting variable string as file name

I'm trying to create a file with a unique file name for every time my script runs. I am only intending to do this to every week or month. so I chose to use the date for the file name.
f = open('%s.csv', 'wb') %name
is where I'm getting this error.
Traceback (most recent call last):
File "C:\Users\User\workspace\new3\stjohnsinvoices\BabblevoiceInvoiceswpath.py", line 143, in <module>
f = open('%s.csv', 'ab') %name
TypeError: unsupported operand type(s) for %: 'file' and 'str'
it works if I use a static filename, is there an issue with the open function, that means you can't pass a string like this?
name is a string and has values such as :
31/1/2013BVI
Many thanks for any help.
You need to put % name straight after the string:
f = open('%s.csv' % name, 'wb')
The reason your code doesn't work is because you are trying to % a file, which isn't string formatting, and is also invalid.
you can do something like
filename = "%s.csv" % name
f = open(filename , 'wb')
or f = open('%s.csv' % name, 'wb')
Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance
f = open('{}.csv'.format(name), 'wb')
Another option - the f-string formatting (ref):
f = open(f"{name}.csv", 'wb')
And with the new string formatting method...
f = open('{0}.csv'.format(name), 'wb')
Even better are f-strings in python 3!
f = open(f'{name}.csv', 'wb')
import hashlib
filename = file_for_download
with open(filename, "rb") as f:
bytes = f.read() # read entire file as bytes
msg_hash = hashlib.sha256(bytes).hexdigest();
print(f"MSG_HASH = {msg_hash}")

Categories

Resources