Python Forum
How can i fix json.decoder.JSONDecodeError ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can i fix json.decoder.JSONDecodeError ?
#1
Hello, how do I solve this problem?

import json

def write_json(new_date, filename='data.json'):
    try:
        
        with open(filename, 'r+') as file:
            #First we load existing data into a dict. (Önce mevcut verileri bir dict'e yüklüyoruz)
            file_data = json.load(file)
    

            file_data["emp_details"].append(new_date)

            # Sets file's current position at offset. (Dosyanın geçerli konumunu ofset olarak ayarlar.)
            file.seek(0)

            # convert back to json. (Json'a dönüştür.)

            json.dump(file_data, file, indent=4)

            #  python object to be appended (Eklenecek python nesnesi)
    except json.decoder.JSONDecodeError:
        return
    
        
y = {"emp_name":"Nikhil",
    "email": "[email protected]",
    "job_profile": "Full Time"
    }

write_json(y)
    
Error:
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Reply
#2
Your current snippet raise different error

Error:
Traceback (most recent call last): File "***", line **, in <module> write_json(y) File "***", line **, in write_json file_data["emp_details"].append(new_date) TypeError: list indices must be integers or slices, not str
JgKSuperstar likes this post
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
file_data = json.load(file)
When you do this file_data it's a dictionary.
Then on line-11 can not use .append as that method is only for list.
For dictionary can use .update
Don't use try: except with return nothing,when test out stuff want to see all errors.
Quick test working.
import json
from pprint import pprint

def write_json(new_date, filename='data.json'):
    with open(filename, 'r+') as file:
        file_data = json.load(file)
        #print(file_data)

        file_data["scripts"].update(new_date)
        #pprint(file_data)
        file.seek(0)
        json.dump(file_data, file, indent=4)

if __name__ == '__main__':
    y = {
        "emp_name": "Nikhil",
        "email": "[email protected]",
        "job_profile": "Full Time",
    }
    write_json(y)
JgKSuperstar likes this post
Reply
#4
(Oct-30-2021, 11:21 AM)buran Wrote: Your current snippet raise different error

Error:
Traceback (most recent call last): File "***", line **, in <module> write_json(y) File "***", line **, in write_json file_data["emp_details"].append(new_date) TypeError: list indices must be integers or slices, not str


I'm sorry, the code I gave you is wrong. No blocks try and except.
Reply
#5
(Oct-30-2021, 12:16 PM)snippsat Wrote:
file_data = json.load(file)
When you do this file_data it's a dictionary.
Then on line-11 can not use .append as that method is only for list.
For dictionary can use .update
Don't use try: except with return nothing,when test out stuff want to see all errors.
Quick test working.
import json
from pprint import pprint

def write_json(new_date, filename='data.json'):
    with open(filename, 'r+') as file:
        file_data = json.load(file)
        #print(file_data)

        file_data["scripts"].update(new_date)
        #pprint(file_data)
        file.seek(0)
        json.dump(file_data, file, indent=4)

if __name__ == '__main__':
    y = {
        "emp_name": "Nikhil",
        "email": "[email protected]",
        "job_profile": "Full Time",
    }
    write_json(y)


I'm getting the same mistake again. Could it be that when we turn it on to read mode, the "data.json" file is empty and gives it this error?

[Image: jdec33t.png]';" src="[Image: jdec33t.png]" alt="İmage" id="maximage" title="Click Photo To Enlarge">
Reply
#6
You don't show content of data.json.
Here is my test with a random validated json file.
data.json before:
{
    "devDependencies": {
        "eslint": "^6.8.0",
        "eslint-config-prettier": "^6.10.1",
        "prettier": "^2.0.2"
    },
    "scripts": {
        "eslint": "eslint . --fix",
        "eslint:check": "eslint .",
        "lint": "npm run prettier && npm run eslint"
    },
    "dependencies": {
        "@jsxtools/resize-observer": "^1.0.4"
    }
}
import json
from pprint import pprint
 
def write_json(new_date, filename='data.json'):
    with open(filename, 'r+') as file:
        file_data = json.load(file)
        #print(file_data)
 
        file_data["scripts"].update(new_date)
        #pprint(file_data)
        file.seek(0)
        json.dump(file_data, file, indent=4)
 
if __name__ == '__main__':
    y = {
        "emp_name": "Nikhil",
        "email": "[email protected]",
        "job_profile": "Full Time",
    }
    write_json(y)
data.json after:
Output:
{ "devDependencies": { "eslint": "^6.8.0", "eslint-config-prettier": "^6.10.1", "prettier": "^2.0.2" }, "scripts": { "eslint": "eslint . --fix", "eslint:check": "eslint .", "lint": "npm run prettier && npm run eslint", "emp_name": "Nikhil", "email": "[email protected]", "job_profile": "Full Time" }, "dependencies": { "@jsxtools/resize-observer": "^1.0.4" } }
Reply
#7
(Oct-30-2021, 04:33 PM)snippsat Wrote: You don't show content of data.json.
Here is my test with a random validated json file.
data.json before:
{
    "devDependencies": {
        "eslint": "^6.8.0",
        "eslint-config-prettier": "^6.10.1",
        "prettier": "^2.0.2"
    },
    "scripts": {
        "eslint": "eslint . --fix",
        "eslint:check": "eslint .",
        "lint": "npm run prettier && npm run eslint"
    },
    "dependencies": {
        "@jsxtools/resize-observer": "^1.0.4"
    }
}
import json
from pprint import pprint
 
def write_json(new_date, filename='data.json'):
    with open(filename, 'r+') as file:
        file_data = json.load(file)
        #print(file_data)
 
        file_data["scripts"].update(new_date)
        #pprint(file_data)
        file.seek(0)
        json.dump(file_data, file, indent=4)
 
if __name__ == '__main__':
    y = {
        "emp_name": "Nikhil",
        "email": "[email protected]",
        "job_profile": "Full Time",
    }
    write_json(y)
data.json after:
Output:
{ "devDependencies": { "eslint": "^6.8.0", "eslint-config-prettier": "^6.10.1", "prettier": "^2.0.2" }, "scripts": { "eslint": "eslint . --fix", "eslint:check": "eslint .", "lint": "npm run prettier && npm run eslint", "emp_name": "Nikhil", "email": "[email protected]", "job_profile": "Full Time" }, "dependencies": { "@jsxtools/resize-observer": "^1.0.4" } }

My json file is empty
Reply
#8
If the json file is not empty, the yes code does not give an error
Reply
#9
(Oct-30-2021, 10:12 PM)squad Wrote: If the json file is not empty, the yes code does not give an error
If start with empty file can not use json.load(file) on that file.
Make the the structure you want first with a dictionary,then json.dump to make it json file.
Example.
import json
from pprint import pprint

def write_json(new_date, filename='d.json'):
    json_make = {}
    with open(filename, 'r+') as file:
        json_make["emp_details"] = new_date
        file.seek(0)
        json.dump(json_make, file, indent=4)

if __name__ == '__main__':
    y = {
        "emp_name": "Nikhil",
        "email": "[email protected]",
        "job_profile": "Full Time",
    }
    write_json(y)
Output:
{ "emp_details": { "emp_name": "Nikhil", "email": "[email protected]", "job_profile": "Full Time" } }
JgKSuperstar likes this post
Reply
#10
(Oct-30-2021, 10:18 PM)snippsat Wrote:
(Oct-30-2021, 10:12 PM)squad Wrote: If the json file is not empty, the yes code does not give an error
If start with empty file can not use json.load(file) on that file.
Make the the structure you want first with a dictionary,then json.dump to make it json file.
Example.
import json
from pprint import pprint

def write_json(new_date, filename='d.json'):
    json_make = {}
    with open(filename, 'r+') as file:
        json_make["emp_details"] = new_date
        file.seek(0)
        json.dump(json_make, file, indent=4)

if __name__ == '__main__':
    y = {
        "emp_name": "Nikhil",
        "email": "[email protected]",
        "job_profile": "Full Time",
    }
    write_json(y)
Output:
{ "emp_details": { "emp_name": "Nikhil", "email": "[email protected]", "job_profile": "Full Time" } }

I'm sorry for troubling you. Thank you very much for your patience and help my problem has been solved :) <3
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  JSONDecodeError: Expecting value mehtamonita 1 1,518 Mar-07-2022, 04:24 PM
Last Post: bowlofred
  Problems with JSONDecodeError arsouzaesilva 0 1,427 Sep-22-2021, 06:33 PM
Last Post: arsouzaesilva
  coding a decoder... Popkhorn 2 2,109 May-28-2020, 07:26 AM
Last Post: Popkhorn
  reset on inactivity (building a morse decoder) gerrit1985 7 3,542 Apr-17-2020, 10:22 AM
Last Post: deanhystad
  UTF-8 decoder reports bad byte that is not there Skaperen 0 2,293 Oct-11-2018, 04:46 AM
Last Post: Skaperen
  MP4 decoder jdewk 4 5,570 Jan-13-2018, 10:02 PM
Last Post: jdewk
  JSON Decoder issue Cronax3 2 9,773 Sep-13-2017, 09:23 AM
Last Post: Cronax3

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020