Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
json load problem
#1
So I have the attached code, which works, MOSTLY

The source codes are attached (1 class file, and main file) to preserve spacing, etc.  The main purpose of the code is to work with importing class...

when running the main file ...for example entering FOO (for name) BAR (for key) and MOO (for value) then [y] then FOOBAR0 (for filename)...this works fine.
Exit program
Rerun ...enter FOO (for name, again) BAR (for key) and MOO (for value) then [y] then FOOBAR0 (DON'T CHANGE FILENAME) and it yields an error.  BUt if you go to terminal/command prompt and you will see that ALL data is in FOOBAR0.json  

SO: my question is what makes json.load break when I use it for an already existing file - like the 2nd time I run the program


#userdict0.py

import json
from userdict0cl import D

dname=str(input('select dictionary name: '))
dname= D()

while True:
	keyy=str(input('enter key: '))
	if keyy =='':
		break
	else:
		vall = str(input('enter value: '))
	dname.fill(keyy,vall)
dname.printall()

saveyesno=str(input('want to save dictionary? [y/n] '))
if saveyesno =='n' or saveyesno =='':
	print('ok.')
else:
	txt=str(input('enter file name. '))
	txtfile = txt+'.json'
	print('you\'re file is: ' + txtfile)
	dname.write_items(txtfile)
	print('well done.')
	dname.print_json()
#userdict0cl.py
import json
class D():
	def __init__(self):
		self._items = {}
	def fill(self,a,b):		
		self.a = a
		self.b = b
		self._items[self.a]=self.b
	def printall(self):
		print(self._items)
		return self._items
	def write_items(self,filename):
		self._filename=filename
		with open(self._filename, 'a+') as f:
			json.dump(self._items, f)
			f.close()
	def print_json(self):
		with open(self._filename, 'r') as f:
			fn = json.load(f)
			#fn.seek(0)
			print(fn)
			f.close()

.py   userdict0cl.py (Size: 486 bytes / Downloads: 599)
.py   userdict0.py (Size: 544 bytes / Downloads: 530)
Reply
#2
Please, unless it is really big project, post your code in code tags, don't attach py files. See BBcode help for more info. This will make easier to answer and will attract more answers.

I added these for your this time.


Your problems comes every time when you use the same file name you append the json object to the file. As a result what you get is not A valid json file. e.g. after two 'runs' your json file will look like this
Output:
{"bar": "moo"}{"bar": "moo"}
you need to rethink your logic - e.g. load the json file and then append the new key-value pairs and then overwrite the existing file.

there are other problems with your code

1. you overwrite dname immediately
dname=str(input('select dictionary name: '))
dname= D()
first it is a string, a "name" and immediately you use same variable for D instance, so you lost the name

2. It is better to implement __str__() method instead of print_json()
see https://docs.python.org/3/reference/data...tomization

3. unless you write to file, before you print, you will not have _filename property set and this will rise an error. i.e. if you try to print the json, before you write it to file.
Reply
#3
But I am writing (write_items()) first then printing (print_json())

I can remove dname as string. That's fairly easy.

Can you offer a working example? I'm hopelessly lost ...
Reply
#4
Here's an example that creates two json files, and can read it back for a test
This requires python 3.2 or later

it will create two json files in a sub-directory named data

EnigmaPaths.py
from pathlib import Path

class EnigmaPaths:
    def __init__(self):
        self.homepath = Path('.')
        self.datapath = self.homepath / 'data'
        self.imagepath = self.homepath / 'image'
        self.enigma_info = self.datapath / 'enigma_info.json'
        self.color_info = self.datapath / 'color_info.json'
        self.patchboard_image = self.imagepath / 'patchboard.ppm'
InitializationData.py
import EnigmaPaths
import json


class InitializationData:
    def __init__(self):
        self.epath = EnigmaPaths.EnigmaPaths()
        self.epath.datapath.mkdir(exist_ok=True)
        self.init_data = {
            'rotor_info': {
                'rotor1_info': {
                    'name': 'rotor1',
                    'cipher': 'EKMFLGDQVZNTOWYHXUSPAIBRCJ',
                    'notches': ['R'],
                },
                'rotor2_info': {
                    'name': 'rotor2',
                    'cipher': 'AJDKSIRUXBLHWTMCQGZNPYFVOE',
                    'notches': ['F']
                },
                'rotor3_info': {
                    'name': 'rotor3',
                    'cipher': 'BDFHJLCPRTXVZNYEIWGAKMUSQO',
                    'notches': ['W']
                },
                'rotor4_info': {
                    'name': 'rotor4',
                    'cipher': 'ESOVPZJAYQUIRHXLNFTGKDCMWB',
                    'notches': ['K']
                },
                'rotor5_info': {
                    'name': 'rotor5',
                    'cipher': 'VZBRGITYUPSDNHLXAWMJQOFECK',
                    'notches': ['A']
                },
                # Rotor 6 - 8 available on Kriegsmarine M3 and M4 only
                'rotor6_info': {
                    'name': 'rotor6',
                    'cipher': 'JPGVOUMFYQBENHZRDKASXLICTW',
                    'notches': ['A', 'N']
                },
                'rotor7_info': {
                    'name': 'rotor7',
                    'cipher': 'NZJHGRCXMYSWBOUFAIVLPEKQDT',
                    'notches': ['A', 'N']
                },
                'rotor8_info': {
                    'name': 'rotor8',
                    'cipher': 'FKQHTLXOCBJSPDZRAMEWNIUYGV',
                    'notches': ['A', 'N']
                },
            },
            'reflector_B': 'YRUHQSLDPXNGOKMIEBFZCWVJAT',
            'reflector_C': 'FVPJIAOYEDRZXWGCTKUQSBNMHL',
            'unencoded': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        }
        with self.epath.enigma_info.open('w') as f:
            json.dump(self.init_data, f)


class Colors:
    '''
        Colors from the the w3schools themes website:
        main: https://www.w3schools.com/w3css/w3css_colors.asp
        themes: https://www.w3schools.com/w3css/w3css_color_themes.asp
        and specifically portions of the w3-theme-black theme css for this
        theme can be found here:  https://www.w3schools.com/lib/w3-theme-black.css
    '''
    def __init__(self):
        self.epath = EnigmaPaths.EnigmaPaths()
        self.color_theme_black = {
            '.w3_theme_l5': {
                'color': '#000',
                'background-color': '#f0f0f0'
            },
            '.w3-theme-l4': {
                'color': '#000',
                'background-color': '#cccccc'
            },
            '.w3-theme-l3': {
                'color': '#fff',
                'background-color': '#999999'
            },
            '.w3-theme-l2': {
            'color': '#fff',
                'background-color': '#666666'
            },
            '.w3-theme-l1': {
                'color': '#fff',
                'background-color': '#333333'
            },
            '.w3-theme-d1': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme-d2': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme-d3': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme-d4': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme-d5': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme-light': {
                'color': '#000',
                'background-color': '#f0f0f0'
            },
            '.w3-theme-dark': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme-action': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-theme': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-text-theme': {
                'color': '#000000'
            },
            '.w3-border-theme': {
                'border-color': '#000000'
            },
            '.w3-hover-theme:hover': {
                'color': '#fff',
                'background-color': '#000000'
            },
            '.w3-hover-text-theme': {
                'color': '#000000'
            },
            '.w3-hover-border-theme': {
                'border-color': '#000000'
            }
        }

        with self.epath.color_info.open('w') as f:
            json.dump(self.color_theme_black, f)

    def test_read(self):
        with self.epath.color_info.open() as f:
            self.init_data = json.load(f)

if __name__ == '__main__':
    InitializationData()
    Colors()
Reply
#5
hmmm. Your examples are totally above my head (I'm only learning python now on 3.6). I realize those are a peace of cake to you but I'm not there yet. I'm actually still trying to understand the point of

if __name__ == '__main__':
   obj.method()
maybe you're willing to run through that? I know the syntax but don;'t really see why I want apply it to my code. Never had a problem with

obj.method()
Reply
#6
if __name__ == '__main__':
   obj.method()
This allows the program to execute code differently, depending on how it's started

To illustrate how this works, create the following two very short program:

short.py
def func1():
    print('__name__: {}'.format(__name__))

func1()
stillshort.py
import short

short
Now from a command line, first run:
python short.py
result:
Output:
__name__: __main__
now run:
python stillshort.py
result:
Output:
__name__: short
So, the if
__name__ == '__main__':
will only be true if the program was called directly.
Reply
#7
I never should have thrown that example at you without modification,
I just grabbed it from a project.

Here's a simpler example:
import json


def make_json():
   init_data = {
       'rotor1_info': {
           'name': 'rotor1',
           'cipher': 'EKMFLGDQVZNTOWYHXUSPAIBRCJ',
           'notches': ['R'],
       }
   }

   with open('simple.json', 'w') as f:
       json.dump(init_data, f)


def test_read():
   mydata = {}
   with open('simple.json') as f:
       mydata = json.load(f)

   for key, value in mydata.items():
       print('key: {}, Value: {}'.format(key, value))


if __name__ == '__main__':
   make_json()
   test_read()
running get these results:
Output:
key: rotor1_info, Value: {'name': 'rotor1', 'cipher': 'EKMFLGDQVZNTOWYHXUSPAIBRCJ', 'notches': ['R']}
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with nested JSON Kalet 7 1,396 Dec-09-2021, 11:13 PM
Last Post: Gribouillis
  Problem With Database Calls and Load Timbo03 1 1,501 Nov-21-2021, 10:48 AM
Last Post: Timbo03
  Problem with Json Array kwekey 2 1,076 Aug-02-2021, 05:11 PM
Last Post: kwekey
  Problem to parse a json enigma619 3 1,577 Dec-04-2020, 08:16 AM
Last Post: enigma619
  Python - help with getting JSON from one DB and load to another DB qIekm 4 1,984 Apr-16-2020, 07:07 AM
Last Post: qIekm
  json problem enigma619 9 2,513 Dec-19-2019, 08:29 AM
Last Post: enigma619
  problem with mapnik in anaconda python 2: from _mapnik import * ImportError: DLL load parsley 0 1,391 Dec-11-2019, 07:50 AM
Last Post: parsley
  Output to a json file problem Netcode 3 2,667 Nov-22-2019, 01:44 AM
Last Post: Skaperen
  Load JSON file data into mongodb using pymongo klllmmm 1 10,732 Jun-28-2019, 12:47 AM
Last Post: klllmmm
  json.load causing IndexError: list index out of range WallyZ 5 4,932 May-20-2019, 01:11 PM
Last Post: WallyZ

Forum Jump:

User Panel Messages

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