Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python Hates me
#5
I'm no expert, but I try to get things to work how I want them.

I don't really use json, but this is something I did to learn a bit about json. I just adapted it to your data.

Just change the paths for your paths, then paste myApp() in your shell to try it.

def myApp():    
    # get the modules
    import json
    from pathlib import Path

    """
    When you load the .json file with data = json.load(f) you have a dictionary of dictionaries
    Then you can do all the things Python dictionaries can do.
    """

    mypath = '/home/pedro/temp/datasets1.json'

    # check if the json you want exists
    chk_file = Path(mypath) 
    if chk_file.is_file():
        print(mypath, 'exists, so open it ... \n\n')
        with open(mypath) as f:
            data = json.load(f)
    else:
        print("File does not exist, so make data an empty dictionary!\n\n")
        data = {}     


    # collect data
    # this is a list of things we need to know about each product

    collect_data = ['date', 'url','description','inbound', 'outbound']

        # a function to collect our data
    # this function returns a dictionary with product data
    # this dictionary is saved in the list: product_data

    def get_dataset():
        data_dict = {}
        print('First get client_id and check it ... ')
        dataset_id = input('Please enter the dataset_id like: dataset1 ')
        # check if this key exists, if so, don't accept it
        # the dataset_id must be unique, so use the dict.get(key) method
        while not data.get(dataset_id) == None:
            print('This dataset id is already in use, try again.')
            dataset_id = input('Please enter the dataset_id: \n\n')        
        # now we have a unique dataset_id
        print('Please now enter the details for the dataset with dataset id', dataset_id)
        for info in collect_data:            
            data_dict[info] = input(f'Please enter the {info}: ')
        data[dataset_id] = data_dict
        

    replies = ['yes', 'no']
    reply = 'X'
    # still need a way to keep the product ids unique!!
    while not reply in replies:    
        print('Do you want to enter 1 or more new datasets?')
        reply = input('Enter yes to continue, enter no to stop ')
        if reply == 'yes':
            answers = get_dataset()
            reply = 'maybe'
        elif reply == 'no':
            break

    for key in data.keys():
        print('dataset_id is', key)
        print('date is:', data[key]['date'])
        print('url is:', data[key]['url'])
        print('description is:', data[key]['description'])
        print('inbound is:', data[key]['inbound'])
        print('outbound is:', data[key]['outbound'])

    # save the data dictionary as a .json file
    # USE YOUR PATH    
    # open 'w' and overwrite the existing file
    
    print('Now saving the client data, run myApp() again to add more clients later ... ')
    with open(mypath, 'w') as json_file:
        json.dump(data, json_file)
    print('data saved to', mypath)

    # open the file you just saved in mypath to inspect it
    # USE YOUR PATH
    print('Now reopening', mypath, 'to have a look at the data ... ')
    with open(mypath) as f:
      data = json.load(f)

    print('data is ', len(data), 'entries long')

    # look at the content of '/home/pedro/temp/datasets1.json'

    for item in data.items():
        print(json.dumps(item, indent = 4, sort_keys=True))

    # because of the way the data was collected,
    # inbound or outbound contain "True" or "False" as strings not True or False as boolean
    for key in data.keys():
        if data[key]['inbound'] == "True":
            print('url is:', data[key]['url'])
            print('dataset[\'inbound\'] is', data[key]['inbound'])

    print('All done, byebye!')

    """
    You can open and append to this json file any time
    """
Reply


Messages In This Thread
Python Hates me - by quarinteen - Aug-12-2022, 02:08 PM
RE: Python Hates me - by rob101 - Aug-12-2022, 02:41 PM
RE: Python Hates me - by deanhystad - Aug-12-2022, 03:39 PM
RE: Python Hates me - by Gribouillis - Aug-12-2022, 09:47 PM
RE: Python Hates me - by Pedroski55 - Aug-13-2022, 04:38 AM

Forum Jump:

User Panel Messages

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