admin管理员组

文章数量:1327800

I have this variable on my ponent's state:

chartData: {
            labels:null,
            datasets:null
        }

I receive this json from my api to create the chart:

{
"labels": [
    "13/7",
    "14/7",
    "15/7"
],
"datasets": [
    {
        "label": "%%%%",
        "data": [
            0,
            18,
            168
        ],
        "backgroundColor": [
            "rgba(255, 99, 132, 0.6)",
            "rgba(255, 99, 132, 0.6)",
            "rgba(255, 99, 132, 0.6)"
        ]
    }
]

}

The chart appears with no problem but when I try to print the value of this.state.chartData this appears:

TypeError: Converting circular structure to JSON --> starting at object with constructor 'HTMLCanvasElement' | property '__reactInternalInstance$khbtn4bp50s' -> object with constructor 'FiberNode' --- property 'stateNode' closes the circle

Here is the setState of the variable:

this.setState({
        chartData: {

            datasets: response.datasets,
            labels:response.labels
        }
    })

the response is the json above.

UPDATED METHOD JUST TO PRINT VALUES:

 teste=()=>{

    alert("chart data")

    alert(JSON.stringify(this.state.chartData))

}

edit1: print of the console.log(this.state.chartData)

edit 2: api call:

    return fetch(url, {

        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
            labels:params.labels,
            datasets:params.datasets
        })

    }).then(response => response.json())
        .then(json => {
            console.log("fetchJsonFromApi " + JSON.stringify(json))
            // making callback optional
            if (callback && typeof callback === "function") {
                callback(json);
            }
            return json;
        })
        .catch(error => {
            console.log(error)
        });

}

I have this variable on my ponent's state:

chartData: {
            labels:null,
            datasets:null
        }

I receive this json from my api to create the chart:

{
"labels": [
    "13/7",
    "14/7",
    "15/7"
],
"datasets": [
    {
        "label": "%%%%",
        "data": [
            0,
            18,
            168
        ],
        "backgroundColor": [
            "rgba(255, 99, 132, 0.6)",
            "rgba(255, 99, 132, 0.6)",
            "rgba(255, 99, 132, 0.6)"
        ]
    }
]

}

The chart appears with no problem but when I try to print the value of this.state.chartData this appears:

TypeError: Converting circular structure to JSON --> starting at object with constructor 'HTMLCanvasElement' | property '__reactInternalInstance$khbtn4bp50s' -> object with constructor 'FiberNode' --- property 'stateNode' closes the circle

Here is the setState of the variable:

this.setState({
        chartData: {

            datasets: response.datasets,
            labels:response.labels
        }
    })

the response is the json above.

UPDATED METHOD JUST TO PRINT VALUES:

 teste=()=>{

    alert("chart data")

    alert(JSON.stringify(this.state.chartData))

}

edit1: print of the console.log(this.state.chartData)

edit 2: api call:

    return fetch(url, {

        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify({
            labels:params.labels,
            datasets:params.datasets
        })

    }).then(response => response.json())
        .then(json => {
            console.log("fetchJsonFromApi " + JSON.stringify(json))
            // making callback optional
            if (callback && typeof callback === "function") {
                callback(json);
            }
            return json;
        })
        .catch(error => {
            console.log(error)
        });

}
Share edited Jul 17, 2019 at 14:39 Vencovsky 31.7k22 gold badges130 silver badges197 bronze badges asked Jul 17, 2019 at 14:09 carlos carlos 631 gold badge1 silver badge4 bronze badges 7
  • but when I try to print the value of this.state.chartData how do you print it? – Vencovsky Commented Jul 17, 2019 at 14:14
  • I have created a button just to print the variable, updated the question – carlos Commented Jul 17, 2019 at 14:16
  • Why do you need to print it with JSON.stringify? Are you reserializing aggregated data? – inetphantom Commented Jul 17, 2019 at 14:22
  • use console.log(...) or console.dir(...) instead of alert(JSON.stringify(...)). – Thomas Commented Jul 17, 2019 at 14:23
  • The problem is that there is not any circular reference.Updated the question with print of the console.log. I need to seralize because I use that same json as the cody of my request, updated the question with that method too @Thomas – carlos Commented Jul 17, 2019 at 14:29
 |  Show 2 more ments

3 Answers 3

Reset to default 4

What happens here is that JSON.stringify cannot be used for circular data. Circular data is when you have an object that references some other parent object. If JSON.stringify printed some circular data, it would be a infinity string.

This probably happen because you are getting some circular data from the response.

If you really want to print it and ignore the circular that, you can take a look at this question that have alot of ways to do so.

What I remend is using console.log instead of alert and in the console you will be able to see circular data with no problem.

Here is a demo for showing circular data, wich is taken from this answer.

// Demo: Circular reference
var o = {};
o.o = o;

// Note: cache should not be re-used by repeated calls to JSON.stringify.
var cache = [];
JSON.stringify(o, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Duplicate reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

var a = {b:1}
var o = {};
o.one = a;
o.two = a;
// one and two point to the same object, but two is discarded:
console.log(JSON.stringify(o))

To remove _meta (wich maybe have circular data) you can do:

if(Array.isArray(response.datasets){
    let newDataSets = response.datasets.map(({label, data, backgroundColor}) => ({label, data, backgroundColor}))
    // do what you want to do
}

If you experience this issue while running your react app locally while using joi-browser npm package. If its work before and it does not work again

I experience the same error when I changed the content of the object variable which I link to my form.

Kindly shutdown the app then start it again

yarn start
npm start

this might help someone, I had the same issue and solved it by menting the code I put after. The issue happened because the function was called twice.

before:
    afunctionCall()
    return;
    aFunctionCall()
after:
    afunctionCall()
    // return;
    // aFunctionCall()

本文标签: javascriptcircular structure to JSON in reactStack Overflow