我花了几个小时,尝试了所有在网上找到的东西,拉了一些留在我头上的头发... 我已将此JSON发送到我正在编写的Flask Web服务中:
{'jsonArray': '[
{
"nom":"0012345679",
"Start":"2018-08-01",
"Finish":"2018-08-17",
"Statut":"Validee"
},
{
"nom":"0012345679",
"Start":"2018-09-01",
"Finish":"2018-09-10",
"Statut":"Demande envoyée au manager"
},
{
"nom":"0012345681",
"Start":"2018-04-01",
"Finish":"2018-04-08",
"Statut":"Validee"
},
{
"nom":"0012345681",
"Start":"2018-07-01",
"Finish":"2018-07-15",
"Statut":"Validee"
}
]'}
我只想遍历记录:
app = Flask(__name__)
@app.route('/graph', methods=['POST'])
def webhook():
if request.method == 'POST':
req_data = request.get_json()
print(req_data) #-> shows JSON that seems to be right
##print(type(req_data['jsonArray']))
#j1 = json.dumps(req_data['jsonArray'])
#j2 = json.loads(req_data['jsonArray'])
#data = json.loads(j1)
#for rec in data:
# print(rec) #-> This seems to consider rec as one of the characters of the whole JSON string, and prints every character one by one
#for key in data:
# value = data[key]
# print("The key and value are ({}) = ({})".format(key, value)) #-> TypeError: string indices must be integers
for record in req_data['jsonArray']:
for attribute, value in rec.items(): #-> Gives error 'str' object has no attribute 'items'
print(attribute, value)
我相信我在JSON对象,python dict对象,字符串之间迷路了,但我不知道自己缺少什么。我确实试图将通过json.dumps和json.loads方法接收的JSON放入,但仍然没有。我想念什么??
我只是想遍历每条记录以创建另一个python对象,将其馈入这样的图表库中:
df = [dict(Task="0012345678", Start='2017-01-01', Finish='2017-02-02', Statut='Complete'),
dict(Task="0012345678", Start='2017-02-15', Finish='2017-03-15', Statut='Incomplete'),
dict(Task="0012345679", Start='2017-01-17', Finish='2017-02-17', Statut='Not Started'),
dict(Task="0012345679", Start='2017-01-17', Finish='2017-02-17', Statut='Complete'),
dict(Task="0012345680", Start='2017-03-10', Finish='2017-03-20', Statut='Not Started'),
dict(Task="0012345680", Start='2017-04-01', Finish='2017-04-20', Statut='Not Started'),
dict(Task="0012345680", Start='2017-05-18', Finish='2017-06-18', Statut='Not Started'),
dict(Task="0012345681", Start='2017-01-14', Finish='2017-03-14', Statut='Complete')]
答案 0 :(得分:1)
整个内容都用单引号引起来,这意味着它是一个字符串,您需要对其进行解析。
for record in json.loads(req_data['jsonArray']):
看看您评论的代码,您这样做:
j1 = json.dumps(req_data['jsonArray'])
data = json.loads(j1)
在字符串上使用json.dumps
是错误的主意,而且json.loads(json.dumps(x))
与x
相同,因此可以将您带回到开始的地方,即{{1} }与data
(一个字符串)相同。
这是正确的主意:
req_data['jsonArray']
但您从未使用过j2 = json.loads(req_data['jsonArray'])
。
如您所见,遍历字符串会为您提供字符串的每个字符。