I have the following JSON document:
[
{
"iLevel": 85,
"isEthereal": true,
"quality": "Normal",
"stats": [
{
"name": "item_splashonhit",
"value": 100
}
],
"type": "Legendary Mallet"
},
{
"defense": 720,
"iLevel": 88,
"isEthereal": true,
"quality": "Normal",
"sockets": 4,
"type": "Diamond Mail"
},
{
"defense": 732,
"iLevel": 69,
"isEthereal": true,
"quality": "Normal",
"type": "Boneweave"
}
]
Here is the code I've put together so far and the error. I think that it is perhaps the JSON format which is wrong?
# packages
import json
from json import JSONEncoder
from pathlib import Path
from typing import Collection
# get all json files in 'json' folder
folderPath = '.\\json\\'
jsonFiles = (f for f in Path(folderPath).glob("*") if f.is_file())
for j in jsonFiles:
fileCont = open(j.resolve())
for f in fileCont:
obj = json.loads(f)
print(obj.name, obj.quality, obj.ilevel, obj.type)
fileCont.close()
I also don't think I am using the 'json' library correctly. Sorry I am still very new to python.
Error:
Traceback (most recent call last):
File "C:\Users\username\script.py", line 17, in <module>
obj = json.loads(d)
File "C:\Users\username\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\username\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\username\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 2 column 1 (char 3)
Any help is appreciated. Once I get through this I'll be looking to iterate through the 'stats' object as well but I'll cross that bridge later. I just want 'print()' to output the values so I know I am working with objects correctly.
The is one subtle trick, which you should pay attention for and thats the load functionality of json :
json.loads() - should be used for a string-like files
json.load() - should be used for a file-like objects
So if i was you, I would start like this :
for j in jsonFiles:
with open(j, "r") as f:
t = json.load(f)
for i in t:
i.get("stats") # returns None if nothing found
Related
This question already has answers here:
Why can't I call read() twice on an open file?
(7 answers)
Closed last year.
with open(LATEST_UPDATE_FULL_PATH) as JSON_FILE_UPDATE:
JSON_DATA_UPDATE = json.load(JSON_FILE_UPDATE)
JSON_DATA_UPDATE = json.load(JSON_FILE_UPDATE)
why does doing "load" twice causes the following below?
Is there a handle on this file? I could not find anything to release JSON_FILE_UPDATE.
Traceback (most recent call last):
File "PhthonScript", line 69, in <module>
JSON_DATA_UPDATE = json.load(JSON_FILE_UPDATE)
File "...\PythonByMiniconda3\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "...\PythonByMiniconda3\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "...\PythonByMiniconda3\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "...\PythonByMiniconda3\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)
try this:
JSON_DATA_UPDATE = json.loads(JSON_FILE_UPDATE)
once it is loaded, then the file converted to json. cannot convert json to json.
another way, this may work on string to json:
import ast
file = """{
"students": [
{
"name": "Millie Brown",
"active": False,
"rollno": 11
},
{
"name": "Sadie Sink",
"active": True,
"rollno": 10
}
]
}"""
print(type(file))
dict = ast.literal_eval(file)
print(type(dict))
dict['students'][0]['name'] would be "Millie Brown"
dict['students'][1]['active'] would be True
This is my ciao.json that i need to parse some data from it
{
"opcua": [
{
"ip": ciao,
"port": 4840,
"uri": "http://examples.freeopcua.github.io"}
"objects":[
{
object_name: ListaDeiSensori,
variables:[
"Temperature_Sensor",
"Water_Sensor"]
}]
}]
}
To pase the fileds of the json file i am using this python script:
import json
with open('ciao.json') as file:
data = json.load(file)
print(data
But i get this error:
Traceback (most recent call last):
File "getdata.py", line 11, in <module>
data = json.load(file)
File "/usr/lib/python3.6/json/__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/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 4 column 28 (char 72)
Is there anyone that can help me in solving this problem?
I do not know how to solve it...
I think there are some errors in the json file.
update json, I changed undefined obj to string.
{
"opcua": [
{
"ip": "ciao",
"port": 4840,
"uri": "http://examples.freeopcua.github.io"
},
{
"objects": [
{
"object_name": "ListaDeiSensori",
"variables": [
"Temperature_Sensor",
"Water_Sensor"
]
}
]
}
]
}
I'm new to Python. I'm working on a script to send notifications on overdue Asana tasks. I'm running into issues with converting the Asana API response, which is a JSON with multiple objects that represent tasks, to Python objects. For now, all I want to do is convert the JSON objects into Python objects to validate the response.
This is what the raw JSON response from Asana looks like:
{
"data": [
{
"gid": "1234567891234567",
"due_on": "2021-02-12",
"name": "My First Task",
"permalink_url": "https://app.asana.com/0/123456789/1234567891234567"
},
{
"gid": "1234567891234568",
"due_on": "2021-02-26",
"name": "My Second Task",
"permalink_url": "https://app.asana.com/0/123456789/1234567891234568"
},
{
"gid": "1234567891234569",
"due_on": null,
"name": "My Third Task",
"permalink_url": "https://app.asana.com/0/123456789/1234567891234569"
}
]
}
My Python code looks like the following:
import json
import asana
taskList = []
with open('./work_in_progress.json') as f:
for jsonObj in f:
taskDict = json.loads(jsonObj)
taskList.append(taskDict)
print("Printing each JSON Decoded Object")
for task in taskList:
print(task["gid"], task["name"], task["due_on"], task["permalink"])
However, when I run it, I get the following error:
Traceback (most recent call last):
File "test.py", line 9, in <module>
taskDict = json.loads(jsonObj)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 2 (char 1)
Any help would be appreciated.
Have you tried the following? Replace the with statement with this code:
with open('./work_in_progress.json') as f:
taskDict = json.load(f)
taskList.append(taskDict)
I get the below error when i try to read a JSON file, not sure what needs to be corrected:
C:\Users\prabhjot2600\PycharmProjects\PythonPractise\venv\Scripts\python.exe C:/Users/prabhjot2600/Desktop/Prabh/alien_invasion/test.py
Traceback (most recent call last):
File "C:/Users/prabhjot2600/Desktop/Prabh/alien_invasion/test.py", line 26, in <module>
data = json.loads(people_string)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.7_3.7.1776.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 11 column 21 (char 192)
My code is simply reading a JSON file and printing its data. I have checked my JSON data also which looks correct and also formatted it to see if there were any errors left but still cant read the JSON
import json
people_string = '''
{
"people": [
{
"name": "Prabhjot Singh",
"phone": "9999596310",
"emails": [
"prabh#noemail.com",
"prabhjot#ranamail.com"
],
"hasLicence": True
},
{
"name": "Sunny Rana",
"phone": "9999988888",
"emails": null,
"hasLicence": False
}
]
}
'''
data = json.loads(people_string)
print(data)
JSON stands for JavaScript Object Notation.
So it is subset of Javascript's syntax.
Javascript uses true and false keyword as literal boolean values.
(Whereas python uses True and False).
Therefore, you should use true and false instead of True and False.
See https://www.json.org/json-en.html for detailed syntax.
I am stuck here again... I have a file named "data.json" and I want to open it with python but I am getting errors.
import json
>>> data=json.load(open("data.json"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\Angel\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 340,
in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 4912995)
>>>
According to Python JSON documentation
If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
Not knowing the content of your file, it is hard to say what is wrong, but I would suspect that text in your file is not a valid JSON object, or more likely (according to "Extra data" search, answered here) the file "data.json" includes more than one JSON object.
For example, using your code:
This file works correctly
{ "name":"John", "age":30, "car":null }
but this one
{ "name":"John", "age":30, "car":null }
{ "name":"John", "age":30, "car":null }
throws the same errors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py",
line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py",
line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\a\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py",
line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 6 column 1 (char 55)
In case 2 or more than 2 record, you have to reformat your file as mentioned below OR you have to load file record by record.
You need to reformat your json to contain an array like below:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}