Search code examples
pythonjsongetrequest

Getting response from URL after changing config.json properties with Python


How can i resolve problem in Python?

  1. Read config.json file located in : /data/python/config.json make a GET request to the URL under ‘url’ key and add the first 15 characters to a key name ‘content’ in the json file.
  2. config.json: {"url": "https://www.google.com"}
  3. config.json after code run: {"url": "https://www.google.com", "content": ""} Where should be the first 15 characters from the response.

Solution

  • This is the code, that will help you to get what you want

    Note: you will need to install requests library before running the code. pip install requests

    import json
    
    import requests
    
    with open("/data/python/config.json", "r") as f:
        config = json.load(f)
    
    result = requests.get(config['url'])
    
    config['content'] = result.text[:15]
    
    with open("config.json", "w") as f:
        json.dump(config, f)
    

    It does simple things:

    1. Loads config.json from json to python dict
    2. Gets url value from it
    3. Sends request using requests library
    4. Adds content slice of length 15 to a dict with a key content
    5. Saves updated dictionary to config.json