11
  dfList = df.values.tolist()
  return jsonify(dfList)

I have this as result, it's actualy removing the variable names of the DataFrame and replacing them with integers

-0: [
  0: "Les abeilles sont dehors",
  1: "ObservationNature",
  2:  0.6790075732725341,
  3:  [],
],
-1:[
  0: "elle sont allée chercher le miel à coté des fleurs du rucher",
  1: "ObservationNature",
  2: 0.4250480624587389,
  3: [],
]

my result should look like this, with the varibales that are in the DataFrame

-0: [
  "texte": "Les abeilles sont dehors",
  "type": "ObservationNature",
  "nluScore":  0.6790075732725341,
  "ruche":  [],
],
-1:[
  "texte": "elle sont allée chercher le miel à coté des fleurs du rucher",
  "type": "ObservationNature",
  "nluScore": 0.4250480624587389,
  "ruche": [],
],

5 Answers 5

14

Use df.to_json() and set mimetype='application/json'

for example:

from flask import Response
@app.route("/dfjson")
def dfjson():
    """
    return a json representation of the dataframe
    """
    df = get_dataframe_from_somewhere()
    return Response(df.to_json(orient="records"), mimetype='application/json')
2
6

That's because you're passing ndarray type to jsonify.

Although df.to_json(orient="records") will serve you right, you can achieve your specific format through df.iterrows() and/or defaultdit Here is an example:

@app.route('/')
def pandasJSON():
    df2 = pd.DataFrame({'A': 1.,
                        'C': pd.Series(1, index=list(range(4)), dtype='float32'),
                        'D': np.array([3] * 4, dtype='int32'),
                        'E': pd.Categorical(["test", "train", "test", "train"]),                    
                        'F': 'foo'})

    df2['G'] = [100,200,300,400]
    df2.set_index('G', inplace=True)
    result = {}
    for index, row in df2.iterrows():
        #result[index] = row.to_json() 
        result[index] = dict(row)
    return jsonify(result)

Output Image

2

Look in pandas documentation

df.to_json(orient='records')
'[{"col 1":"a","col 2":"b"},{"col 1":"c","col 2":"d"}]'

Encoding/decoding a Dataframe using 'index' formatted JSON:

df.to_json(orient='index')
'{"row 1":{"col 1":"a","col 2":"b"},"row 2":{"col 1":"c","col 2":"d"}}'

Encoding/decoding a Dataframe using 'columns' formatted JSON:

df.to_json(orient='columns')
'{"col 1":{"row 1":"a","row 2":"c"},"col 2":{"row 1":"b","row 2":"d"}}'

Encoding/decoding a Dataframe using 'values' formatted JSON:

df.to_json(orient='values')
'[["a","b"],["c","d"]]'
1

If you run

df.to_json(orient="records")

it should provide you with the output that you want (note: as of Pandas version 0.23.3)

0

transform df to dictionary: jsonify(df.to_dict())

see below:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/dfjson")
def dfjson():
    """
    return a json representation of the dataframe
    """
    return jsonify(df.to_dict())

see Doc for different configurations

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.