Home > database >  React includes \n in Json returned from Flask API
React includes \n in Json returned from Flask API

Time:12-06

I´ve defined an end point in my FLASK API app as follows:

@app.route("/get_data", methods=["GET"])
def get_data():
    collection = mongo.db["colection_name"]
    query_results = collection.find_one()
    return jsonify(list(query_results))

It returns the data from MongoDB in JSON format and I can perfectly fetch it in Python using the requests library, which look as follows:

[
  {
    "date": "Sat, 01 Jan 1983 00:00:00 GMT",
    "tmed": 5.9
  },
  {
    "date": "Sun, 02 Jan 1983 00:00:00 GMT",
    "tmed": 4.4
  }, ...
]

However, when I call it from my React app using the following format

const getData = async () => {
      try {
        const res = await axios.get(
          `http://127.0.0.1:5000/get_data`
        );
        setData(res.data);}

It returns it in an unformatted string manner, where \n are added. That makes React to not consider the data as an array and subsequently to not display it correctly. That is the format in which React receives the data:

'[\n  {\n    "date": "Sat, 01 Jan 1983 00:00:00 GMT" \n "tmed ..... }\n]\n'

I am not sure if the issue is in the Flask or in the React side. Any way to make Flask correctly return the data or React to consume it correctly?

CodePudding user response:

replace the \n and parse the json

 const res = await axios.get(
      `http://127.0.0.1:5000/get_data`
    );

    const result = JSON.parse(res.data.replace('\n', ''))

    setData(result.data);}

CodePudding user response:

The underlying problem was some NaN values generated in my Python component and included in the JSON. JavaScript doesn´t deal with NaN but Null values and does not understand the first. That turned the returned object into a large string rather than a real JSON.

Once I replaced the NaN values in my Python module with None values, JavaScript correctly turned them into Null, and the JSON was imported correctly.

  • Related