Parsing JSON

Parsing JSON from the Web

import time
import board
from adafruit_pyportal import PyPortal

# Set up where we'll be fetching data from
DATA_SOURCE = "https://www.adafruit.com/api/quotes.php"
QUOTE_LOCATION = [0, 'text']
AUTHOR_LOCATION = [0, 'author']

# the current working directory (where this file is)
cwd = ("/"+__file__).rsplit('/', 1)[0]
pyportal = PyPortal(url=DATA_SOURCE,
                    json_path=(QUOTE_LOCATION, AUTHOR_LOCATION),
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"/quote_background.bmp",
                    text_font=cwd+"/fonts/Arial-ItalicMT-17.bdf",
                    text_position=((20, 120),  # quote location
                                   (5, 210)), # author location
                    text_color=(0xFFFFFF,  # quote text color
                                0x8080FF), # author text color
                    text_wrap=(35, # characters to wrap for quote
                               0), # no wrap for author
                    text_maxlen=(180, 30), # max text size for quote & author
                   )

# speed up projects with lots of text by preloading the font!
pyportal.preload_font()

while True:
    try:
        value = pyportal.fetch()
        print("Response is", value)
    except (ValueError, RuntimeError) as e:
        print("Some error occured, retrying! -", e)
    time.sleep(60)

JSON

The neat part is that the text is not coming from a file on the device (see how to do this next), but rather it is grabbed from a website!

Adafruit.com has a PHP script at the adafruit.com/api/quotes.php page. Each time it is requested, it returns a new quote from a large database of quotes.

In fact, you can run the same query the PyPortal does to see the results. Copy and paste this link: https://www.adafruit.com/api/quotes.php

into your browser and you'll see a result like this:

[
  {
    "text": "Science, my lad, is made up of mistakes, but they are mistakes which it is useful to make, because they lead little by little to the truth",
    "author": "Jules Verne"
  }
]

That result is the quote formatted as a JSON (JavaScript Object Notation) array. It is comprised of a single element with two keys: text and author.

  • The value of the text key is Science, my lad, is made up of mistakes, but they are mistakes which it is useful to make, because they lead little by little to the truth
  • The value of the author key is Jules Verne

Since this JSON object has a consistent way to return the results to us, the code we're running on the PyPortal can easily parse the data and display it!

You can see how it's done in this part of code.py:

Download: file
# Set up where we'll be fetching data from
DATA_SOURCE = "https://www.adafruit.com/api/quotes.php"
QUOTE_LOCATION = [0, 'text']
AUTHOR_LOCATION = [0, 'author']

Then, in the pyportal query we ask for the text and author name from that URL, and then use the text_ arguments to set the fontpositioncolorwrap, and maxlen of the text when it is displayed.

Download: file
pyportal = PyPortal(url=DATA_SOURCE,
                    json_path=(QUOTE_LOCATION, AUTHOR_LOCATION),
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd+"quote_background.bmp",
                    text_font=cwd+"fonts/Arial-ItalicMT-17.bdf",
                    text_position=((20, 40),  # quote location
                                   (5, 190)), # author location
                    text_color=(0xFFFFFF,  # quote text color
                                0x8080FF), # author text color
                    text_wrap=(35, # characters to wrap for quote
                               0), # no wrap for author
                    text_maxlen=(180, 30), # max text size for quote & author
                    )

With all of this prepared, during the main loop of while True: the code will query the Adafruit quotes page for the JSON data, and display it, and then wait one minute until repeating the process.

Parsing local JSON files 

If you would like to avoid pulling data from a web page or maybe you can't get access to a specific API key, you can use a "local" JSON file to pull data from.

To implement this local data sourcing method, create a new file and name it local.txt. Populate this file with the JSON data that you would like to use. For example, you could use the JSON data provided above and make sure the format of the data is the same. Save this file on the CIRCUITPY drive in the root.

You should not need to change anything in your code.

And that's it! The JSON data will now be pulled from this local file!

This guide was first published on Feb 26, 2019. It was last updated on Feb 26, 2019. This page (Parsing JSON) was last updated on Mar 29, 2020.