Python Forum
json with regex script snagging
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
json with regex script snagging
#1
Hi -

I wrote a simple py script to basically act as a password json repository. Yes, I'm aware I could accomplish this is many different ways (even with a simple text file instead of a json file), but I wanted to practice my json syntax and regex.

Basically, the script has 3 parts.
-1st asks for some site (this is the key in the json dict) and then for the password value.
-2nd The json file should open and a simple re.search looks to match the password entered with some json element. It prints the site name and the password
-3rd if none is found the script appends the site and the password to the json file.

here is my script
#!/usr/bin/env python3


#pwkpr0.py

import json, os, sys, random
from functools import partial

os.chdir('/home/me/Desktop')
print(os.getcwd())

def askme(question,type,errmsg):
	while True:
		the_input = input(question)
		if the_input !='':
			try:
				the_input = type(the_input)
			except ValueError:
				print(f'{the_input} {errmsg}')
				continue
			else:
				print(f'{the_input} is acceptable...')
				return the_input
		else:
			print('can\'t be left empty. Try again.')
			continue

your_info = {}

ask_away = partial(askme,type=str, errmsg='is not a string')

def pull_file():
	get_site = ask_away('enter site')
	get_info = ask_away('password for site')
	filen='pwholder.json'
	with open(filen,'a+') as f:
		file_contents = json.load(f)#code snags here...is any thing wrong with this syntax?
		print(file_contents)
		pull_up(file_contents)
	choice = ask_away('type \'again\' to start again\n\'leave\' to leave.')
	if choice == 'again' or choice == 'a':
		pull_file()
	else:
		print('thank you for using pwkpr...best of luck not getting hacked...')
		print('logging out in 2 secs...')
		sys.exit()	

def pull_up(file_contents):
	get_site
	get_site.strip().lower()
	locate = re.search(r'get_site',file_contents)#search for get_site value in file_contents
	if locate:
		print(f'your {get_site} password is: {your_info[get_site]}')
	else:
		print('no entry found...we\'ll make one.')
		make_entry()

#filen is theoretically open when make_entry() is called...
#bc filen stays open for duration of pull_up()
def make_entry():
	print('In a few moments, you will be asked for this site\'s password')
	sys.sleep(2)
	get_info
	your_info[get_site] = get_info
	json.dump(your_info,f)

if __name__=='__main__':
	print('we can begin...')
	pull_file()
else:
	print(f'sorry {__name__} can\'t be imported...')
my traceback
[inline]
Traceback (most recent call last):
File "pwkpr0.py", line 69, in <module>
pull_file()
File "pwkpr0.py", line 37, in pull_file
file_contents = json.load(f)
[/inline]

I figured I'd have some debugging to do, but I couldn't figure this out.
Reply
#2
There should be a error type after your error that you are missing. What kind of traceback are you getting?
Recommended Tutorials:
Reply
#3
(Jan-31-2018, 05:27 PM)metulburr Wrote: There should be a error type after your error that you are missing. What kind of traceback are you getting?

Nope. here's the traceback in its entirety: Huh
Quote:Traceback (most recent call last):
File "pwkpr0.py", line 69, in <module>
pull_file()
File "pwkpr0.py", line 37, in pull_file
file_contents = 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 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Can I infer that my 'logic' here is ok at least? file_contents = json.load(f) causes a problem which I can't figure out, but you guys are also having a tiny bit of difficulty with it as well Big Grin Big Grin . I guess I'm running into 'pretty good' (aka thought provoking) problems?

I'm pretty much stuck. I feel this _should_ work...
Reply
#4
(Jan-31-2018, 07:50 PM)mepyyeti Wrote: you guys are also having a tiny bit of difficulty with it as well Big Grin Big Grin . I guess I'm running into 'pretty good' (aka thought provoking) problems?
No you just never gave the full traceback until now. This is the line we needed to see
Quote:
Error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The last line or few lines is vital as it tells what the error actually is.

I believe you want json.loads(f) as the way you have it, if im correct. json.load(filen) otherwise.

Also are you sure the json file exists?

related thread
https://python-forum.io/Thread-Python-3-...-10?page=2
Recommended Tutorials:
Reply
#5
(Jan-31-2018, 08:13 PM)metulburr Wrote: Also are you sure the json file exists?
Definitely. Initially, the way the script works is that it creates it the very first time around (i've been deleting the files via terminal since the code has been breaking). Vaguely remember fiddling with json.loads() as well and failing...likely I used used the wrong argument. _will play again with it this later today_ (I'm on a windows machine w/out py installed at moment) Thanks! hopefully this works!

Since this is really for practice, how would you optimize the script? Or is it efficient enough for its intended purpose...aka to be a repository for pws (albeit not a very secure one haha...) . Not so much the fact that it's a technically unsecure json file on a desktop with a bunch of passwords lol, (I can always os.chdir() and such) But from a code/syntax pov
Reply
#6
mepyyeti Wrote:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
That mean it almost all cases that the json file is badly formattet(not correctly made).
JSON Formatter
If you want correct format,and a file to test with.
Copy code under and paste into link over,you will see VALID JSON (RFC 4627).
Then Download as File.
{
  "count": 2, 
  "results": [
    {
      "id": 1, 
      "studentld": 50, 
      "lastname": "Simpson", 
      "firstname": "Homer"
    }, 
    {
      "id": 2, 
      "studentld": 100, 
      "lastname": "Superman", 
      "firstname": "Clark"
    }
  ], 
  "meta": {}
}
Reply
#7
(Jan-31-2018, 09:12 PM)snippsat Wrote: That mean it almost all cases that the json file is badly formattet(not correctly made).
I'm sorry haven't had the chance these couple of days to follow up.

I was able to look at metulburr's referenced thread and also your suggested site. I haven't had the chance to experiment. I should pt out the json file...at its genesis IS going to be empty...why would this result in any sort of error (I ask this because the thread metulburr referenced the problem was an empty json file.) In my instance a(n) (empty) json file is correctly. Would the error stem from the variable having an empty value? IE
file_contents = json.load(filename)
is Null if an empty file equates of a 0 value or None?

Is my thinking on the right track?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Script to convert Json to CSV file chvsnarayana 8 2,549 Apr-26-2023, 10:31 PM
Last Post: DeaD_EyE
  Match key-value json,Regex saam 5 5,439 Dec-07-2021, 03:06 PM
Last Post: saam
  regex on json file senaint 12 16,014 May-06-2020, 04:16 AM
Last Post: buran
  [split] script: remove all "carriage return" from my json variable pete 2 2,814 May-05-2020, 03:22 PM
Last Post: deanhystad
  Regex to retrieve data from json in script tag. DreamingInsanity 4 9,603 Dec-20-2019, 06:18 PM
Last Post: DreamingInsanity
  script: remove all "carriage return" from my json variable mfran2002 4 11,230 Feb-20-2019, 05:07 AM
Last Post: mfran2002
  Issue with a script to convert xls to json Will86 2 3,834 Dec-19-2018, 08:23 AM
Last Post: Will86
  Looking for csv to json convertion script rajaniyer123 1 2,885 Jul-06-2017, 10:42 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

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