Home > OS >  Error Converting circular structure to JSON, while sending json from Flask to Node.js
Error Converting circular structure to JSON, while sending json from Flask to Node.js

Time:05-29

I am trying to send a json file from my Flask server to my Node.js server. Unfortunatelly,in the node.js side I am receiving the error :

TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'ClientRequest'
    |     property 'socket' -> object with constructor 'Socket'
    --- property '_httpMessage' closes the circle
    at JSON.stringify (<anonymous>)

I am not sure why I am getting this errr in my particular case after reading other questions in SOF.

My code looks like this in Flask

receipt.py

receiptDict = [
    {
        "date" :"some date",
        "receipt_id": "4456gdffd", 
        "store": "some store", 
        "items" : [{"name":"can of paint", "amount":1, "price":10}, 
        {"name":"bags of sand", "amount":2, "price":5} ],
        "total" : 15
    },
    
    { 
        "date" :"some date",
        "receipt_id": "44575fh",
        "store": "some store",
        "items" : [{"name":"screws", "amount":100, "price":100} ],
        "total" : 15
    }
        ]
main.py

from receipt import receiptDict
from flask import Flask
import json
app = Flask(__name__)


@app.route('/')
def index():
    #convert_json = json.dumps(receiptDict)
    #return convert_json 
    ·return 'hello flask' I get the same error with both returns

if  __name__ == '__main__':
    app.run(debug=True)

And this is my controller in node.js

dashboard.js

getReceiptInfo : async(req, res) =>{
        const receipt = await axios.get('http://127.0.0.1:5000')
        return res.send(receipt)

    }

CodePudding user response:

Use jsonify, it will serialize data to JSON.

from receipt import receiptDict
from flask import Flask, jsonify # <--- import this jsonify here
import json
app = Flask(__name__)


@app.route('/')
def index():
    return jsonify(receiptDict)

if  __name__ == '__main__':
    app.run(debug=True)

More info on jsonify

Also on your controller do

 return res.send(receipt.data)

axios by default convert response to JSON, Use <response>.data instead of <response>

  • Related