skip to Main Content

When I’m typing commands one at a time in my console, I get these results:

content = "{ "hello":"world" }"
'{ "hello":"world" }'

JSON.parse(content)
{hello: 'world'}

Object.keys(JSON.parse(content))
['hello']

This is the desired result, because I’m trying to .forEach the keys. However, in my React app, I’m trying to use this code:

  React.useEffect(() => {
    axios.get(`${API_ENDPOINT}/appointments/24/goal_notes/1.json`).then((response) => {
      const content = response?.data?.content
      console.log(content);
      console.log(JSON.parse(content));
      console.log(Object.keys(JSON.parse(content)));
      // setAppointmentNoteContent(response?.data?.content);
    });
  }, []);

But I’m getting this result:

"{ "hello":"world" }"
{ "hello":"world" }
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']

So it’s like the third log is treating the object as a string, even though it was parsed.

Is this possibly because, in the React app, the value of content is coming from a .json column from my Rails backend?

How can I access the keys and values of this object?

2

Answers


  1. I’m sorry that I can’t comment because my reputation is not enough.

    The attached code is different from the actual code, or the environment seems strange.

    That code works as expected.

      const content = "{ "hello":"world" }"
      console.log(content)
      console.log(JSON.parse(content))
      console.log(Object.keys(JSON.parse(content)))
    
      console.log(Object.keys(content))

    my guess is your code uses content not JSON.parse(content)

    Login or Signup to reply.
  2. Judging by the output, your content might be a string literal of a JSON string of a JSON string (somehow got JSON.stringifyed twice).

    Make sure your JSON string is { "hello":"world" }(length: 19) but not "{ "hello":"world" }"(length: 25), in that case you need to JSON.parse it twice to get the correct output, but you should be focused on how did you get that string in the first place (e.g. avoid using JSON.stringify on a string, fix malformed JSON file, using correct Content-Type on a JSON request: application/json etc.)

    let content = "{ "hello":"world" }"
    
    console.log("length", content.length);
    console.log(content);
    console.log(JSON.parse(content));
    console.log(Object.keys(JSON.parse(content)));
    let content = '"{ \"hello\":\"world\" }"';
    
    console.log('length', content.length);
    console.log(content);
    console.log(JSON.parse(content));
    console.log(Object.keys(JSON.parse(content)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search