While trying to convert the following string into JSON object, I got an error. How can I fix it?
text = '{ "MonitorGroupGuid": "e8b20230-70b6-4348-36f3e3f", "Description": "Root CA", "IsAll":False}'
JsonObject = json.loads(text)
Output:
x = json.loads(x)
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/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 98 (char 97)
You can simply use "" for False are use 0/1, but if you want it as a bool object use false without quotes
"False" datatype is string
just false datatype bool
text = '{ "MonitorGroupGuid": "e8b20230-70b6-4348-36f3e3f", "Description": "Root CA", "IsAll":"False"}'
JsonObject = json.loads(text)
print(JsonObject)#{'MonitorGroupGuid': 'e8b20230-70b6-4348-36f3e3f', 'Description': 'Root CA', 'IsAll': 'False'}
Replace False with false (without quotes)
text = '{ "MonitorGroupGuid": "e8b20230-70b6-4348-36f3e3f", "Description": "Root CA", "IsAll":false}'
JsonObject = json.loads(text)
print(JsonObject) #{'MonitorGroupGuid': 'e8b20230-70b6-4348-36f3e3f', 'Description': 'Root CA', 'IsAll': False}
Related
I am trying to create an REST API and a part of the project requires working with JSON files.
I am trying to open a JSON file, to check whether certain content exists in the file. If it doesn't, it will be added. For that reason, I am trying to load the JSON file in order to use the dictionary methods. When I open the file and try to use the json.loads() function, I get an error. I am attaching the part of the code that doesn't work.
file = open(self.storage_file_name, 'r')
if file_is_empty:
content_to_write = json.dumps(self.states_population_json, indent=4)
file.write(content_to_write)
else:
current_date = str(date.today())
print(file.read())
json_content = json.loads(file.read()) # THIS IS WHERE THE ISSUE APPEARS <<<
if current_date in self.states_population_json["features"].keys():
pass
else:
json_content["features"][current_date] = self.states_population_json["features"][current_date]
Here's the error as well:
Traceback (most recent call last):
File "C:\Users\denis\AppData\Local\Programs\Python\Python39-32\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 tried using json.load() instead of json.loads(), but then I get the following error:
Traceback (most recent call last):
File "C:\Users\denis\Desktop\Programming\ESRI_Internship\test_file.py", line 89, in <module>
data.save_data_json()
File "C:\Users\denis\Desktop\Programming\ESRI_Internship\test_file.py", line 79, in save_data_json
json_content = json.load(file)
File "C:\Users\denis\AppData\Local\Programs\Python\Python39-32\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\denis\AppData\Local\Programs\Python\Python39-32\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\denis\AppData\Local\Programs\Python\Python39-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\denis\AppData\Local\Programs\Python\Python39-32\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)
Process finished with exit code 1
I made sure that the file isn't empty.
Thanks in advance!
EDIT:
Here is the content of the file (shortened a bit):
{
"features": {
"2022-01-06": [
{
"STATE_NAME": "Alabama",
"POPULATION": 5028316
},
{
"STATE_NAME": "North Carolina",
"POPULATION": 10736879
},
{
"STATE_NAME": "North Dakota",
"POPULATION": 321419
}
]
}
}
The line print(file.read()) moves the file cursor for reading to the end of the file (the command reads the whole file). A subsequent file.read() thus will not be able to read anything. Just remove the print statement, or if needed, move the file cursor back to the beginning of the file by executing file.seek(0) before the json.loads() statement.
I have a simple python program that should load a .json file into a variable and print the variable output to the screen. But it fails to run and errors with the following message:
"File "/Documents/VSCode/python-3-programming-specialization/Data Collection and Processing with Python (Course 3)/Lesson 1/assessment6.py", line 5, in <module>
res = json.load(json_file,)
File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/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 15 column 25 (char 506)"
In the JSON file there is an error too that I think is the problem but I don't know what values to set to clear the error in the JSON file. The error occurs anywhere you see a None, True or False value.
JSON error message: "Value expected json(516)
"statuses": [
{
"contributors": None,
"truncated": False,
"text": "RT #mikeweber25: I'm decommiting from the university of Michigan thank you Michigan for the love and support I'll remake my decision at the\u2026",
"in_reply_to_status_id": None,
"id": 536624519285583872,
"favorite_count": 0,
"source": "Twitter for iPhone",
"retweeted": False,
"coordinates": None,
import json
with open('./tweets.json') as json_file:
res = json.load(json_file)
print(res)
The expected output should be the file read in by the python program.
I want to create a temporary JSON file to store the google calendar credentials, that were stored in a "job" object.
I am using the ServiceAccountCredentials to then get the credentials from the file.
Client = {
"clientID": job.getClientID(),
"clientSecret": job.getClientSecret()
}
temp = tempfile.NamedTemporaryFile(mode="w+b", suffix=".json")
complex_data = open(temp.name, "w", encoding="UTF-8")
complex_data.write(json.dumps(Client))
# data = complex_data.write(json.dumps(Client))
# z = json.loads(data)
credentials = ServiceAccountCredentials.from_json(
temp.name
)
```
I get the following error:
Traceback (most recent call last):
File "/var/www/library-offers-google-calendar/main.py", line 209, in <module>
temp.name
File "/var/www/library-offers-google-calendar/venv/lib/python3.7/site-packages/oauth2client/service_account.py", line 436, in from_json
json_data = json.loads(_helpers._from_bytes(json_data))
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/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)
From the docs, the method ServiceAccountCredentials.from_json accepts a json data rather than a json file name.
If you want to use a json file name, you need to use the method ServiceAccountCredentials.from_json_keyfile_name
Or else, you can directly use Client dictionary as a parameter to ServiceAccountCredentials.from_json without creating and reading from temporary file.
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)
I am trying to convert a dictionary object into json, but unable to do so. I tried json.load(), json.loads() but it gives me following error:
File "lean.py", line 252, in createJSON
return json.loads(jsonElementDict)
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())
TypeError: expected string or buffer
When I print dictionary object, it's as follows:
{
'city': 'Pittsburgh',
'state': 'Pennsylvania',
'gross_floor_area': '',
'energyData': [
{
'cdd': '0.0',
'reading': '80.8',
'monthYear': 'Nov-2014'
},
{
'cdd': '0.0',
'reading': '300000.0',
'monthYear': 'Nov-2014'
}
]
}`
Code:
outputJSON = json.loads(jsonElementDict)
print outputJSON.json['city']