Python: why does repeat of json.load cause error [duplicate] - python

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

Related

having trouble understanding how to load json and iterate through it

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

Problem in parsing data of a JSON file with Python

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"
]
}
]
}
]
}

Unable to read a JSON file in my simple python code

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.

how to open json file in python

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}
]
}

self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ','

I have a large json file (2.4 GB). I want to parse it in python. The data looks like the following:
[
{
"host": "a.com",
"ip": "1.2.2.3",
"port": 8
},
{
"host": "b.com",
"ip": "2.5.0.4",
"port": 3
},
{
"host": "c.com",
"ip": "9.17.6.7",
"port": 4
}
]
I run this python script parser.py to load the data for parsing::
import json
from pprint import pprint
with open('mydata.json') as f:
data = json.load(f)
Previously, I made this post about the same code. I am trying to run the code with larger RAM. but I got a different error. Can you please help me identify the source of the problem?
Traceback (most recent call last): File "parser.py", line 6, in
data = json.load(f) 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 355, in raw_decode
obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1095583 column 749 (char 56649111)
There is a similar problem in this post but I could not use the solution as I read my json array from a file. Not sure how to apply the solution in this case?

Categories

Resources