0

I am passing URLs to a filtering service. The json body I post is:

body = {
    "url-filter": [
        "www.reddit.com",
        "www.cnn.com",
        "www.espn.com"
    ]
}

I would like to create a function that will allow me to pass one or more URLs to filter. What is unclear to me is:

1) How I should pass these URLs to a function - Python list? The URLs do not need to retain order/sequence.

2) How I should insert the URLs into this json body?

Is there a function that will do this or is something more required?

2 Answers 2

1

You can simply do this:

body['url-filter'].append("www.myaddress.com")

If you want to add multiple URLs, do this to add a list of URLs:

body['url-filter'] += list_of_urls
Sign up to request clarification or add additional context in comments.

Comments

1

You're asking two questions here, the first one is how you pass the URLs to a function, the second is how you add another URL to the list.

The code that you show is valid python code for a dictionary with one single key url-filter. So you can pass the list of URLs to a python function like this:

myfunction(body['url-filter'])

If you actually meant that body is a json encoded string, you can decode that string using json.loads like this

import json
decoded_body = json.loads(body)

and then you can pass it to a function. If you want to add another URL to the list of URLs, you can simply append that URL by `body['url-filter'].append('www.new-url.com'). This becomes a little more involved if body was actually meant to be a string. You would first want to decode the string into a python object, then append the new url and finally encode everything as json again.

def add_url(body, url):
    json_body = json.loads(body)
    json_body['url-filter'].append(url)
    return json.dumps(json_body)

2 Comments

When I do this, I get backslashes in the json msg. Example:
Where do you get backslashes when you do what?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.