简体   繁体   English

无法在 python 中格式化 a.json 文件

[英]unable to format a .json file in python

I have a python code (main.py) which contains a python module named json which I want to use to store some important key=value pairs in a comfortable manner, that I can use later.我有一个 python 代码(main.py),其中包含一个名为 json 的 python 模块,我想用它以舒适的方式存储一些重要的键=值对,以后可以使用。 The problem is here that the format(structure) .问题在于格式(结构)

For your better understanding I have attached some code here为了您更好地理解,我在此处附上了一些代码

The main.py file contains the main code. main.py文件包含主要代码。 The output.json file shows the output of the main file. output.json文件显示了主文件的output。 The expected_output.json file contains the format(structure) which shows that how I want to store my data(key=value) in general. expected_output.json文件包含格式(结构) ,它显示了我希望如何存储我的数据(键=值)。

If anyone is interested to fork this repository he/she is extreamly invited.如果有人有兴趣分叉这个存储库,他/她受到了极大的邀请。

The code: main.py代码: main.py


############*****Importing Modules*****############

import random as _random # for making random passwords.
import sys as _sys # for taking command line arguments.
import getopt as _getopt # for making command line flags.
import json as _json


############*****String Decleration*****############

_sm_Letter = ['abcdefghijklmnopqrstuvwxyz'] # small letters to use as a string on the user's password.
_cap_Letter = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ'] # capital letters to use as a string on the user's password.
_sp_char = ['!?,:;()-/@_`~#$%=^+&{*}[]|<>\.'] # special charecters to use as a string on the user's password.
_Numbers = ['0','1','2','3','4','5','6','7','8','9'] # numbers to use as a string on the user's password.
_str = _sm_Letter + _cap_Letter + _Numbers + _sp_char # concatinating those lists
_str = ''.join(_str)
_str = _str*100


############*****Defining Command line Options*****############

_args = _sys.argv[1:] # Remove 1st argument (file name) from the list of command line arguments. 
_s_opt = "ahvl:um:" # short options
_l_opt = ["accounts","help","masterkey=","lenght=","version","update"] # long options


############*****Defining Some Imyportant stuffs*****############

def _usage(): #defining usage
    print ("Usage: "+ _sys.argv[0] + " -m [MASTERKEY]\n")
    print ("Example: "+ _sys.argv[0] + " -m your_master_key\n")
def _help(): #defining help section
    _usage()
    print ("A tool for generate random and strong encrypted password and to keep that password also.\n\nMandatory arguments to long options are mandatory for short options too.")
    print ("-a, --accounts          to know how many accounts are exists.")
    print ("-h, --help          you are now seeing this.")
    print ("-l, --lenght            to pass the lenght of your password.")
    print ("-v, --version           to see the version of this tool.")


############*****Creating Masterkey Genaration Algorithum*****############

def _create_Master_Key():
    _masterKey = _random.sample(_str, 1000)
    _masterKey = ''.join(_masterKey)
    print('\nYour password is : '+_masterKey)



############*****Trying To Get Info From The User From The Command Line Arguments*****############

try:
    # Parsing argument
    arguments, values = _getopt.getopt(_args, _s_opt, _l_opt)
    # checking each argument
    for currentArgument, currentValue in arguments:
        if  currentArgument in ("-a", "--accounts"):
            pass
            exit()
        elif currentArgument in ("-h", "--help"):
            _help()
            exit()
        elif currentArgument in ("-v", "--version"):
            print('Version: V1.0.0')
            exit()
        elif currentArgument in ("-l", "--lenght"):
            _pass = _random.sample(_str, int(currentValue))
            _pass = ''.join(_pass)
            print('\nYour password is : '+_pass)
            exit()
        elif currentArgument in ("-m", "--masterkey"):
            print ("Displaying file_name:", _sys.argv[0])
        #elif currentArgument in ("-v", "--version"):
        #   print (("Enabling special output mode (% s)") % (currentValue))
except _getopt.error as err:        
    # output error, and return with an error code       
    print (str(err))
    print ("Enter -h, --help for help.")
    exit()




############*****Taking Info From The User Manually and generating random password*****############

_info = {}
try:
    _len_string = int(input('Enter the lenght of your password :> ')) # for getting the lenght of the user's password.
except:
    print('Please enter valid info')
    exit()

def _main():
    with open('output.json', 'r') as _f:
        data = _json.load(_f)

    _pass = _random.sample(_str,_len_string)
    _pass = ''.join(_pass)
    print('\nYour password is : '+_pass)
    _ans = input('\nDo you want to keep this password[Y/N] :> ')
    if  _ans == 'Y' or _ans == 'y' :
        _user = input('\nEnter User Name :> ')
        _acc_Name = input('\nEnter Account Name :> ')
        _email = input('\nEnter Email :> ')
        _info[_acc_Name] = {
            'name': _user,
            'email': _email,
            'pass': _pass
        }
        data[_acc_Name].append(_info)
        s = _json.dumps(_info, indent=2)
        with open('output.json', 'w') as f:
            f.write(s)      
            exit()
    elif _ans == 'N' or _ans == 'n' :
        _main()
        exit()
    else:
        print('Please enter valid info')
        exit()

if __name__ == '__main__':
    _main()
    _create_Master_Key()

output.json output.json

{
  "facebook": {
    "name": "username",
    "email": "example@email.com",
    "pass": "password"
  }
}{
  "facebook": {
    "name": "username",
    "email": "example@email.com",
    "pass": "password"
  }
}{
  "gmail": {
    "name": "username",
    "email": "example@email.com",
    "pass": "password"
  }
}{
  "gmail": {
    "name": "username",
    "email": "example@email.com",
    "pass": "password"
  }
}

expected_output.json预期输出.json

{
    "facebook": [
        {
            "User": "username",
            "email": "example@email.com",
            "pass": "random_generated_password",
            "created on": "date"
        },
        {
            "User": "username",
            "email": "example@email.com",
            "pass": "random_generated_password",
            "created on": "date"
        }
    ],

    "gmail": [
        {
            "User": "username",
            "email": "example@email.com",
            "pass": "random_generated_password",
            "created on": "date"
        },
        {
            "User": "username",
            "email": "example@email.com",
            "pass": "random_generated_password",
            "created on": "date"
        }
    ]
}

any one please solve this error任何人请解决这个错误

You cannot append an Object to an Object like how the output.json looked like. You cannot append an Object to an Object like how the output.json looked like.

I changed this data[_acc_Name].append(_info) to the following:我将此data[_acc_Name].append(_info)更改为以下内容:

if len(data[_acc_Name]) == 0:
    print('no user for this account')
    data[_acc_Name].append([_info])
else:
    print('users exist for this account')
    data[_acc_Name].append(_info[_acc_Name])

Got this output得到这个 output

{
  "facebook": [
    {
      "name": "yul",
      "email": "noooo@no.com",
      "pass": "z8k7"
    },
    {
      "name": "abc",
      "email": "yyy@gmail.com",
      "pass": "4~R6|)$}"
    }
  ]
}

You might have to add some code to support new account though您可能需要添加一些代码来支持新帐户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM