In my react code I have items as an array in my state.
items[]
I was able to populate items array with few data and need to pass it to my web service. First I need to convert that array to json. This is just crashing for me when I do the Json.stringify.
Is there a different way to do it in react application?
storeDataInDatabase(){
const myObjStr = JSON.stringify(this.props.items);
console.log(myObjStr);
}
In my react code I have items as an array in my state.
items[]
I was able to populate items array with few data and need to pass it to my web service. First I need to convert that array to json. This is just crashing for me when I do the Json.stringify.
Is there a different way to do it in react application?
storeDataInDatabase(){
const myObjStr = JSON.stringify(this.props.items);
console.log(myObjStr);
}
Share
Improve this question
edited Nov 13, 2019 at 15:39
Wang Liang
4,4447 gold badges25 silver badges50 bronze badges
asked Feb 7, 2019 at 19:51
BabaBaba
2,2299 gold badges53 silver badges93 bronze badges
4
-
You said
state
initially then useprops
in your example. Which is it? What is the error? "just crashing for me" doesn't tell us much. – chazsolo Commented Feb 7, 2019 at 19:53 -
What is
items[]
? It looks like you forgot a string in a property accessor, but you're saying it's an array. – jmargolisvt Commented Feb 7, 2019 at 19:53 - If your items = [1, 2, 3], it will bees '[1, 2, 3]' when you do JSON.stringify(items). I don't think you can convert array to json since json is a format. It is not a data structure. I think you mean converting array to object right? – dnp1204 Commented Feb 7, 2019 at 19:56
- Yes I think it is converting array to object – Baba Commented Feb 7, 2019 at 20:01
1 Answer
Reset to default 5JSON.stringify(..)
will convert your array the right way.
The serialized object would be something like:
{
"items": [
{
"key1": "value1",
"key2": "value2"
},
{
"key1": "value1",
"key2": "value2"
}
]
}
But like you wrote in your first sentence, you are setting the items array to state. In think in a way like this:
this.setState({ items })
If so, you have to get the array right from your state in your ponent:
storeDataInDatabase() {
const { items } = this.state;
const myObjStr = JSON.stringify(items);
console.log(myObjStr);
}