如何将字典中的每个值转换为单独的列表?
How to convert each value in a dictionary to a separate list?
所以我试图将 payload
中的值转换为单独的列表。 fruits 的第一个值,我试图将其放在 fruits
列表中,与 vegetables
.
相同
main.py
import requests
headers = {
'Content-Type': 'application/json'
}
list_of_fruits = ["orange", "banana", "mango"]
list_of_vegetables = ["squash", "brocoli", "aspharagus"]
payload = {
"fruits": list_of_fruits
"vegetables": list_of_vegetables
}
response = requests.post(f"127.1.1.1:9000/json", headers=headers, json=payload)
------------------------------------------------------------------------------------------
flask_api.py
from flask import Flask, request
@app.route('/post_json', methods=['POST'])
def process_json():
content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
fruits= []
vegetables = []
data = request.json
for k, v in data.items(): #How can I convert the first list of values to the fruits list? and the same for vegetables?
print(v) ---> ["orange", "banana", "mango"]["squash", "brocoli", "aspharagus"]
return data
else:
return 'Content-Type not supported!'
#Output ---> ["orange", "banana", "mango"]["squash", "brocoli", "aspharagus"]
您需要从请求中读取数据。你的请求是这样的
{
'fruits': ['list of fruits'],
'vegetables': ['list of vegetables']
}
您正在使用 data = requests.json
读取 json 格式的请求数据,其格式与上述格式相同。
现在read/save列表中的数据,需要从data
字典中读取数据并保存在列表中。
fruits = data.get('fruits', []) # [] in case no 'fruits' as key value in payload
vegetables = data.get('vegetables', [])
这里fruits
和vegetables
是您保存数据的列表。
所以我试图将 payload
中的值转换为单独的列表。 fruits 的第一个值,我试图将其放在 fruits
列表中,与 vegetables
.
main.py
import requests
headers = {
'Content-Type': 'application/json'
}
list_of_fruits = ["orange", "banana", "mango"]
list_of_vegetables = ["squash", "brocoli", "aspharagus"]
payload = {
"fruits": list_of_fruits
"vegetables": list_of_vegetables
}
response = requests.post(f"127.1.1.1:9000/json", headers=headers, json=payload)
------------------------------------------------------------------------------------------
flask_api.py
from flask import Flask, request
@app.route('/post_json', methods=['POST'])
def process_json():
content_type = request.headers.get('Content-Type')
if (content_type == 'application/json'):
fruits= []
vegetables = []
data = request.json
for k, v in data.items(): #How can I convert the first list of values to the fruits list? and the same for vegetables?
print(v) ---> ["orange", "banana", "mango"]["squash", "brocoli", "aspharagus"]
return data
else:
return 'Content-Type not supported!'
#Output ---> ["orange", "banana", "mango"]["squash", "brocoli", "aspharagus"]
您需要从请求中读取数据。你的请求是这样的
{
'fruits': ['list of fruits'],
'vegetables': ['list of vegetables']
}
您正在使用 data = requests.json
读取 json 格式的请求数据,其格式与上述格式相同。
现在read/save列表中的数据,需要从data
字典中读取数据并保存在列表中。
fruits = data.get('fruits', []) # [] in case no 'fruits' as key value in payload
vegetables = data.get('vegetables', [])
这里fruits
和vegetables
是您保存数据的列表。