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
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.
my guess is your code uses
content
notJSON.parse(content)
Judging by the output, your
content
might be a string literal of a JSON string of a JSON string (somehow gotJSON.stringify
ed twice).Make sure your JSON string is
{ "hello":"world" }
(length: 19) but not"{ "hello":"world" }"
(length: 25), in that case you need toJSON.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 usingJSON.stringify
on a string, fix malformed JSON file, using correctContent-Type
on a JSON request:application/json
etc.)