When using flask.jsonify, the output is wrapped in square brackets, as opposed to the usual curly

I'm currently facing an issue with my Flask and jsonify setup. When I try to output JSON, it's coming back in array format with square brackets instead of the expected JSON object with curly brackets.

Does anyone have guidance on how to resolve this issue?

The function I'm working on takes text input, uses Spacy to tokenize it, and provides details about each token.

This is the code snippet:

@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)

The current output is like this:

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

I need the JSON response to follow the standard format with curly brackets so that my C# application can deserialize it correctly.

Appreciate any assistance. Thank you!

Answer №1

If you desire a Python dict to be generated by your list comprehension, it is important to keep in mind that the structure needs to initially be established as a list/Array enclosed in square brackets since the key names are consistent for each line or entity.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verification of emails through Mailgun API by interpreting the JSON response

I'm currently working on creating an email validator using the Mailgun API, but I've hit a roadblock when it comes to parsing the JSON response. Here is the code snippet I am using: foreach (string str in this.ema.Items) { HttpWebReques ...

Ensuring visibility remains unaffected by updates in PySimpleGUI

I'm currently facing an issue while attempting to make a GUI element invisible by setting visible=False. It seems that the update function is functioning properly for all attributes and values as shown in the provided code snippet, except for the visi ...

Tips for finding the total of particular elements within an array

I am looking to calculate the sum of elements within an array. To illustrate, I have an array below: [183948, 218520, 243141, 224539, 205322, 203855, 233281, 244830, 281245, 280579, 235384, 183596, 106072, 88773, 63297, 38769, 28343] My goal is to s ...

How to create a 3d plot with dual axes using Python's matplotlib library?

I have been working on creating a 3D plot with two distinct y-axes, similar to the one shown in this research paper. Following instructions from this blog post, I managed to put together a basic example. Required Modules: from mpl_toolkits import mplot3d ...

Exploring geodesic distance calculations on a 3D triangular mesh with the help of scikit-fmm or gdist

I'm currently working on evaluating a geodesic distance matrix for the TOSCA dataset, specifically looking at a 3D mesh example like the one shown below: https://i.stack.imgur.com/CofTU.png During my analysis, I experimented with two different Pyth ...

Create a Flot graph using data from a database

Here is a snippet of jQuery code that I am currently working with: jQuery(document).ready(function () { var formData = "f=27/07/2015&t=01/08/2015"; jQuery.ajax ({ url: 'http://www.yourhealthfoodstore.co.uk/test.p ...

Which one to use: Response JSON object or JSON.stringify()?

If I have JSON content that I want to return, what is the best way to do it? let data = { x: 'apple', y: 'banana' }; Is it better to: A) Return the object as is when sending the response with res.send(data)? B) Convert the objec ...

Unable to determine the dimensions of the Kafka JSON message

My task involves sending a JSON message through Kafka, but my application has limitations on the size of messages it can handle. To construct the message, I am using a Python script. This script reads a base JSON from a file, transforms it, and then saves ...

What steps should be followed to execute the Python class method spausdinti when the object is initialized as obj = Objektas()?

What is the correct way to run the class method spausdinti if the object was initiated like this: obj = Objektas() ? class Objektas: def spausdinti(self): print("Spausdinama") Which answer is accurate? a obj.spausdinti() b spausdinti ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

The Kendo Grid is appearing correctly, however, it is not showing the JSON data as

Lately, I've been struggling with grids, particularly when trying to display properly formatted JSON data fetched from a webservice (which has already been validated in VS2013 and JSONLint). If someone could take a look at my solution and point out wh ...

Utilizing Angular 14 and Typescript to fetch JSON data through the URL property in an HTML

Is there a way to specify a local path to a JSON file in HTML, similar to how the src attribute works for an HTML img tag? Imagine something like this: <my-component data-source="localPath"> Here, localPath would point to a local JSON fil ...

Using lxml in Python: Extracting text displays only English characters while others appear scrambled

Below is the code snippet I'm working with: import requests from lxml.etree import HTML title_req = requests.get("https://www.youtube.com/watch?v=VK3QWm7jvZs") title_main = HTML(title_req.content) title = title_main.xpath("//span[@id='eow-title& ...

Encountering an error while trying to create a React app with npm - module not

Despite having experience with creating numerous React projects, I am encountering an error that I have never seen before. In an attempt to resolve it, I have restarted my computer, cleared my npm cache, and even deleted my package-lock file before running ...

Performing cross-origin GET request

I need help with a scenario involving a link and some JavaScript code. The setup is as follows: <a id="link" href="https://yahoo.com" target="blank">Link</a> Here is the script I'm using: var security = function() { var link ...

JSON.stringify function provides detailed information about the indexes and length of an array

When using AJAX to send an array to my controller, I find it convenient to convert it to JSON format. This is how I construct my array: $("#selectedDropdown option").each(function () { selectedLanguages.push($(this).val()); }); To stringify it, I ...

Error: WebDriverException - Error message: Unable to establish connection with Chrome browser, despite working perfectly just a minute

For the past 15 minutes, my Selenium scraper was functioning perfectly fine until it suddenly started throwing an error every time I run it. Here is the relevant code snippet: searchDate = wait.until(EC.element_to_be_clickable((By.XPATH, "/input[@placehol ...

When passing the output of one function as an argument to another function, an error is occurring known as the 'StaleElementReferenceException'

My Python program consists of two functions - one extracts text from an image using pytesseract, and the other function uses this extracted text to make a Google search with selenium. When I call both functions separately in the same program, they work no ...

Tips for aligning two distinct Dataframe columns to have the same size

What is the best approach to handle two different dataFrame columns that are of unequal sizes? Any advice would be greatly appreciated. For example: df1 = pd.DataFrame(np.random.rand(100,2), columns = list('ab')) df2 = pd.DataFrame(np.r ...

Separate information into columns and save it as a two-dimensional array

Below is the data that I am working with: 49907 87063 42003 51519 21301 46100 97578 26010 52364 86618 25783 71775 1617 29096 2662 47428 74888 54550 17182 35976 86973 5323 ...... My goal is to iterate through it using for line in file. I would like to s ...