Search code examples
pythonjsonparsingflaskurl-routing

How to make a Flask app parse JSON by URL input? ie: website/RedMango opens a page of a RedMango JSON object


To clarify the question, using a Flask URL converter how would one parse the json at this website by entering a url such as: https://ds-med-cabinet.herokuapp.com/strainjson/Purple-Kush so that when the user visits the /Purple-Kush website only that json object is displayed? This website is for building an API for educational purposes only so I would appreciate any ideas pertaining to parsing the entire json by URL input mostly likely using Flask URL converter or any other practical method. Thank you very much for your time and consideration. Here is the code I have tried, as a mock up of the Flask URL Converter documentation:

# Directory.py



# Import

from os import path
import pandas as pd
from flask import Blueprint, render_template
from werkzeug.routing import BaseConverter


# Make Blueprint for __init__.py

Directory = Blueprint("Directory", __name__)


# Import Leafly csv

file_name = path.join(path.dirname(__file__), "Leafly.csv")

df = pd.read_csv(file_name)

strains = df['Strain']



# Custom converter

class ListConverter(BaseConverter):

    def to_python(self, value):
        return value.split('+')

    def to_url(self, values):
        return '+'.join(BaseConverter.to_url(value)
                        for value in values)


# Flask Url-converter

@Directory.route('/<strain>')
def strain_url(strain):
    """Show the json object for the given strain."""
    strain = []
    for strain in strains:
        strain

    return render_template('json.html', strain=strain)
# __init__.py



# Imports

from flask import Flask
from web_app.routes.Directory import Directory, ListConverter
from web_app.routes.GET_PUT_API import GET_PUT_API


# Create Flask app

def create_app():
    
    app = Flask(__name__)

    app.register_blueprint(Directory)
    app.register_blueprint(GET_PUT_API)

    app.url_map.converters['list'] = ListConverter
    
    return app

if __name__ == "__main__":
    my_app = create_app()
    my_app.run(debug=True)

the strains in the for loop is a list of every strain from the csv version of the data, and the json.html being rendered is the html file of json objects that are being rendered at this website. This code and /whateveristypedintheurl just renders all of the data at the website shared (because the html file is already full of json objects and nothing is getting parsed). Thanks again for checking this out.

Ps. If trying to replicate this by creating a Flask App, you can find the csv here as cannabis.csv (I switched the named to Leafly.csv) and you can convert the df to json by using the following code:

# dftojson.py


# Imports

from os import path
import csv
import json


file_path = r'C:\Users\johnj\OneDrive\Documents\Lambda\BuildWeek3\data-science\cannabis.csv'

csvfile = open(file_path, encoding="utf8")
jsonfile = open('cannabis.json', 'w')


fieldnames = ("Strain", "Type", "Rating", "Effects", "Flavor"," Description")
reader = csv.DictReader(csvfile, fieldnames)
for row in reader:
    json.dump(row, jsonfile)
    jsonfile.write('\n')

I copied and pasted the json from cannabis.json into a new json.html file (or just change the file extension) and then added the route like so:

# Directory.py



# Strain JSON Page

@Directory.route("/strainjson")
def df():
    return render_template("json.html")

Solution

  • This is what I came up with. I got built off this article: Medium article on using CSV with Flask. For example locally in your URL you can type ' 5Th-Element' and that should display is JSON format. Adding jsonify on the return will help with API issues.

    import csv
    from os import path
    from flask import Flask, render_template, Blueprint, jsonify, json
    
    
    # Make Blueprint for __init__.py
    
      ParseURL = Blueprint("ParseURL", __name__)
    
    # Import Leafly csv
    
      file_name = path.join(path.dirname(__file__), "Leafly.csv")
    
    
    # route to display single dictionary list item as JSON object
    
    @APP.route('/<strain>')
    def strain_url(strain):
        '''
        Parameters: name of strain from database as a string.
        For loops the cannabis.csv file, creating a dictionary.
        Returning only the strain that was given as a parameter.
        '''
        with open('cannabis.csv') as csv_file:
            data = csv.reader(csv_file, delimiter=',')
            dict_strain = {}
            for row in data:
                if row[0] == strain:
                    dict_strain = {
                        "strain": row[0],
                        "type": row[1],
                        "rating": row[2],
                        "effects": row[3],
                        "flavor": row[4],
                        "description": row[5]
                    }
                    break
        return jsonify(dict_strain)