How can i resolve problem in Python?
- 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.
- config.json: {"url": "https://www.google.com"}
- config.json after code run: {"url": "https://www.google.com", "content": ""} Where should be the first 15 characters from the response.
CodePudding user response:
Welcome to StackOverflow. This is not a site to ask people to write a code.
Next time asking a question, please read this article. You are to show your efforts and show the problems you encounter.
This is the code, that will help you to get what you want
Note: you will need to install
requestslibrary 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:
- Loads
config.jsonfrom json to python dict - Gets
urlvalue from it - Sends request using
requestslibrary - Adds content slice of length 15 to a dict with a key
content - Saves updated dictionary to
config.json
