Search code examples
pythonjsonflaskflask-restfuljsonify

flask.jsonify returns array with square brackets instead of curly brackets


I am using flask and jsonify for the first time and i am stuck at a small problem. My json output is returning an array format with square brackets instead of the json object with curly brackets.

Can someone pls point me in the right direction?

My function takes a text and using spacy breaks it down into tokens and details about the tokens.

my code is-

@app.route('/api/<string:mytext>',methods=['GET'])
def myfunc(mytext):

    docx = nlp(mytext.strip())
    allData = ['Token:{},Tag:{},POS:{}'.format(token.text,token.tag_,token.pos_) for token in docx ]
    
    return jsonify(allData)

It returns the data as

[
  "Token:\",Tag:``,POS:PUNCT", 
  "Token:test,Tag:VB,POS:VERB", 
  "Token:this,Tag:DT,POS:DET", 
]

I want the return JSON to be the standard json response with curly brackets so my c# app can deserialise it properly.

Any help is appreciated.thanks


Solution

  • You want your list comprehension to create a Python dict/curly brackets. It'll still need to be created as a list/Array/square brackets as your key names are the same for each line/entity.

    allData = [{'Token': token.text, 'Tag': token.tag_, 'POS': token.pos_} for token in docx]