Jump to content

Trying to parse a JSON to Alfred Search Results


Recommended Posts

Posted

I'm pretty new (and curious) about Python and recent rediscover Alfred.

I've installed the Alfred Librarys from @deanishe

 

What I am trying to achieve is to get a list of last links created, when user type shsearch, and when select an specific result, pass the id to the next workflow.  

 

 

My code is now like this: 

And i've been trying a lot of ways to parse the results to Script Filter Json format, but couldn't move on.

So, any tips that can help me will be highly appreciated.

I'm also attaching my workflow, just in case. 

Short URL v1.1

 

import requests
import sys
import os
from workflow import Workflow, ICON_WEB, web

url = "https://api.short.io/api/links?domain_id=182191&limit=5&dateSortOrder=desc"

headers = {
    "accept": "application/json",
    "Authorization": os.getenv('SHORT_API_KEY')
}

response = requests.get(url, headers=headers)
response_info =  response.json()


def main(wf):
     url = 'https://api.short.io/api/links?domain_id=182191&limit=5&dateSortOrder=desc'
     params = dict(Authorization=os.getenv('SHORT_API_KEY'), format='application/json')
     r = web.get(url, headers=params)

     # throw an error if request failed
     # Workflow will catch this and show it to the user
     r.raise_for_status()

     # Parse the JSON returned by pinboard and extract the posts
     result = r.json()
     link_list = result['link_list']

     # Loop through the returned posts and add an item for each to
     # the list of results for Alfred
     for link in link_list:
         wf.add_item(title=link['title'],
                     subtitle=link['shortURL'],
                     arg=link['id']
                     icon=ICON_WEB)

     # Send the results to Alfred as XML
     wf.send_feedback()

if __name__ == u"__main__":
     wf = Workflow()
     sys.exit(wf.run(main))

 

Posted
1 hour ago, Rigonatti said:

I've installed the Alfred Librarys from @deanishe


Don’t. That library is for Python 2 only, which no longer ships with macOS. @xilopaint has an updated version for Python 3.

 

But I’ll go further and say you shouldn’t be using a library at all if you’re learning, and instead return what Alfred expects. It’s simple JSON, and understanding how to output that will be useful to your Python/programming learning as a whole, importing the library isn’t gaining you anything in this case.

 

What does the debugger say?

Posted

Thanks for your help @vitor.

Before trying libraries I did try to write requests manually . 

 

Here is the link with the script workflow: ShortIO

 

When I Try to run, the Debugger says only: 

[12:25:40.921] Short URL[Script Filter] Queuing argument '(null)'

 

then, Alfred is frozen and a Have to force quit and reopen .

 

image.thumb.png.8e2f150b8758e35d6d975ed95f652238.png

Posted (edited)

 

 

So, I ended up getting back to python3, per @vitor recommendation.

The code now is: 

import requests
import json

# Importing Variables from os
# import os

# Import Sys to sus.stdout
import sys

# Connecting to the Short IO API Links:

url = "https://api.short.io/api/links?domain_id=182191&limit=5&dateSortOrder=desc"
headers = {
    "accept": "application/json",
    "Authorization": "SHORT_API_KEY"
}

response = requests.get(url, headers=headers)

alfred_items = []

for item in response:
    result = {
        "uid": item["id"],
        "title": item["title"],
        "subtitle": item["originalURL"],
        "arg": item["id"],
    }

    alfred_items.append(result)

response = json.dumps({
    "items": alfred_results
})

sys.stdout.write(response)
 
 
 
 
But, the Debugger keeps getting this message back: 
 
[17:49:45.183] ERROR: Short URL[Script Filter] Code 1: Traceback (most recent call last):
  File "/Users/thiagorigonatti/Dropbox/Alfred Settings/Alfred.alfredpreferences/workflows/user.workflow.7D5AFBA8-06E5-449C-8F09-087F9369FB5C/search.py", line 24, in <module>
    "links": item["links"],
             ~~~~^^^^^^^^^
TypeError: byte indices must be integers or slices, not str
 
I've tried a few ways to solve it, but couldn't be successful. 
 
In time. The JSON API response bellow: 
 
601237775_CleanShot2022-11-24at18_20_20@2x.thumb.png.730639186c54b58f552ec34cc7539c5f.png
 
 
Edited by Rigonatti
update screenshot
Posted
5 hours ago, Rigonatti said:
But, the Debugger keeps getting this message back: 
 
[17:49:45.183] ERROR: Short URL[Script Filter] Code 1: Traceback (most recent call last):
  File "/Users/thiagorigonatti/Dropbox/Alfred Settings/Alfred.alfredpreferences/workflows/user.workflow.7D5AFBA8-06E5-449C-8F09-087F9369FB5C/search.py", line 24, in <module>
    "links": item["links"],
             ~~~~^^^^^^^^^
TypeError: byte indices must be integers or slices, not str

 

That error is from Python, and it’s not for that block of code you posted. There’s no line with the referenced text. You’re triggering something else.

Posted

ops! sorry! 

I've posted the wrong code version. 

Re-postiing to make it clear

 

# Import Sys to sus.stdout
import sys
import json
import requests

# Importing Variables from os
# import os



# Connecting to the Short IO API Links:

url = "https://api.short.io/api/links?domain_id=182191&limit=5&dateSortOrder=desc"
headers = {
    "accept": "application/json",
    "Authorization": "SHORT_API_KEY"
}

response = requests.get(url, headers=headers)

alfred_items = []

for item in response:
    result = {
        "uid": item["id"],
        "title": item["title"],
        "subtitle": item["originalURL"],
        "arg": item["id"],
    }

    alfred_items.append(result)

response = json.dumps({
    "items": alfred_results
})


sys.stdout.write(response)

 

The debugger: 

 

[08:16:52.188] Short URL[Script Filter] Queuing argument ''
[08:16:53.817] Short URL[Script Filter] Script with argv '' finished
[08:16:53.822] ERROR: Short URL[Script Filter] Code 1: Traceback (most recent call last):
  File "PATH/user.workflow.7D5AFBA8-06E5-449C-8F09-087F9369FB5C/search.py", line 25, in <module>
    "uid": item["id"],
           ~~~~^^^^^^
TypeError: byte indices must be integers or slices, not str

 

Posted
4 hours ago, Rigonatti said:
"uid": item["id"],

I am assuming you tried item[id]? Are you sure you get an output from the server? If you provide the actual script (with the API key) I can help troubleshoot. Also, you probably don't need to assign uid for this particular application. 

Posted

three things: 

1. get the json output from the requests call:

response = requests.get(url, headers=headers).json()

 

2. call the links part of the requests object

for item in response['links']:

 

3. "items": alfred_results should be "items": alfred_items

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...