0

Right now, I have a dictionary like this: m = {"score": x, "keywords": {"Mrs. Johnson": 87}} that's being passed from my backend (flask) to my frontend (react), and I want it to be an object when it's passed into the frontend so I can use it as an object and get the value of "score" by using .score.

I'm facing two problems right now, I'm not sure how to pass in a dictionary and have it as an object in react; currently I'm using json.dumps() which I know turns stuff into strings, is there something like that for objects?. Second, once it is passed in as an object, how do I update a pre-existing object (it'll be blank like this data: {}) so that it will be equal to the object I passed in from my backend? Here is my code so far:

BACKEND:

def post(self):
    x = 67
    m = {"score": x, "keywords": {"Mrs. Johnson": 87}}
    return json.dumps(m)

FRONTEND:

class Test extends Component {
    constructor() {
        super()
        this.state = {
          data: {}
        }
    }

    const options = {
        method: "POST",
        headers: {
            'Content-Type': 'application/json', 
        },
        body: JSON.stringify(this.state.text) // Irrelevant
    };
    console.log("hi")
    fetch("http://127.0.0.1:5000/", options)
        .then(response=> response.JSON())
        .then(json => this.setState({data: json}), console.log(this.state.data))

}
Soccerball123
  • 741
  • 5
  • 17

1 Answers1

1

I think jsonify will be used to pass a json object

def post(self):
    x = 67
    m = {"score": x, "keywords": {"Mrs. Johnson": 87}}
    return jsonify({"data": m })   // make sure to import jsonify from flask
Vignesh
  • 302
  • 3
  • 12
  • Thank you this works to pass in an object, but for some reason my react frontend isn't able to `console.log()` the return value I get. I tried setting `{data: json}` but it was still empty. Do you know how to make it so that `data` is equal to `return jsonify({"data": m })`? – Soccerball123 Jan 20 '22 at 04:30
  • I am not sure. but, did you tried using `response.json()` instead of `response.JSON()`? – Vignesh Jan 20 '22 at 04:33
  • Yes, it didn't do anything though – Soccerball123 Jan 20 '22 at 04:51
  • try console.log the value. of json in `.then()`. is the value of json actually an object? – Vignesh Jan 20 '22 at 04:57
  • `'Content-Type': 'application/json;charset=utf-8'`. Try this – Vignesh Jan 20 '22 at 05:00