Python Forum
Python Hates me - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python Hates me (/thread-37946.html)



Python Hates me - quarinteen - Aug-12-2022

I am having the hardest time getting anything to work in python. I am not very familiar with it. I know c# fairly well. I am trying to open a json file and print a specific element from it. Nothing too difficult. Reguardless of what I do or which example I use I always get some error. I do not get it. I have vscode set up exactlty as the example. I copy and paste the code. I renamed my file to be the file name in the example. I keep getting an error about the json file needs to be a string. I get 2 different errors it depends on if I use json.load or json.loads. Any guidance would be appreciated. Below is the very simple code I found and link.

https://www.anycodings.com/1questions/5326853/how-to-extract-elements-from-json-file-with-python
import json
from operator import itemgetter
import os


with open('file.json', 'r') as f:
  data = json.load(f)
  if data['inbound'] == 'true':
    print(data['url'])
this is an example of the json data
Output:
{ "date": "2021-06-14", "url": "https://liveupdate.symantec.com", "description": "Agent Installation Package", "inbound": false, "outbound": true }



RE: Python Hates me - rob101 - Aug-12-2022

I came to Python from C (yes, C, not C++) and although I did not have advanced skills in C, I knew enough to write some reasonable code.

Switching to Python was a bit of a mind shift. The first lesson I learned was that Python has almost everything (if not everything) needed, as is, and as such, I now only (and only if really pushed) ever use an external library if I can't see any other way: Regex being a god example, but (IMHO) people over use it.

Please reformat your code so that it's easier for OPs to read and test it.


RE: Python Hates me - deanhystad - Aug-12-2022

In your json, inbound and outbound are boolean, not strings. In your program you compare data["inbound"] to str "true". This should be:
if data['inbound']:
    print(data['url'])
You could write it this way:
if data['inbound'] == True:
    print(data['url'])
But it is nonsensical testing if the value of a boolean is True.


RE: Python Hates me - Gribouillis - Aug-12-2022

(Aug-12-2022, 02:08 PM)quarinteen Wrote: I keep getting an error about the json file needs to be a string.
Why don't you post the complete error message? Python shows its warmth by providing informative and accurate error messages.


RE: Python Hates me - Pedroski55 - Aug-13-2022

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
    """