Converting component state to JSON in React

43,959

Just use JSON.stringify method in order to turn an javascript object into JSON text and store that JSON text in a string.

Also, you can use JSON.parse which turns a string of JSON text into a Javascript object.

let state = {
    name : "Example",
    age : "21",
    description : "Some text here."
}
console.log(state);
console.log(JSON.stringify(state));

Share:
43,959
Spectrum
Author by

Spectrum

I'm lazy. I like coding, I love IoT. I literally talk to my devices. I'm crazy about music. Jack of all, master of few.

Updated on July 18, 2022

Comments

  • Spectrum
    Spectrum almost 2 years

    I am new to React JS. I wanted to convert the component state data into a JSON object. Is it possible? If so, how?

    Sample state :

    this.state = {
        name : "Example",
        age : "21",
        description : "Some text here."
    }

    That's the whole question. I would appreciate it if you could tell me where I can find simple tutorials to do more advanced things in React (like sending/receiving JSON to/from a server, doing redirects, creating menus, etc). I know I sound vague, and I don't expect very specific answers(if any) to this.

  • Jay Patel
    Jay Patel almost 4 years
    Can I store JSX state value in JSON?