Home > Enterprise >  Object becomes a string after accessing it
Object becomes a string after accessing it

Time:09-26

Backend sends to frontend an Object. Object looks like this: {body: "Items":[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}],"Count":2,"ScannedCount":2}

typeof(obj) returns Object.

When I access "body", typeof(obj["body"]) returns a string and I am unable to retrieve the arrays in the "Items".

console.log(typeof(this.state.message)); // object
const obj = this.state.message;
console.log(obj["body"]); // string

My end goal is to access the data inside "Items" and convert it to a table in render(). Why does my object convert to a string?

Here's the backend code from Lambda:

async function listItems(){
  try {
    const data = await docClient.scan(params).promise()
    return data
  } catch (err) {
    return err
  }
}

exports.handler = async (event, context) => {
  try {
    const data = await listItems()
    return { body: JSON.stringify(data) }
  } catch (err) {
    return { error: err }
  }
}

Here's the frontend Fetch code in ReactJS:

async getData() {
        //this.setState({message: "test"})
        await axios.get("https://...")
        .then((response) => {
            console.log((response)); 
            console.log(typeof(response)); // object
            this.setState({message: response?.data ?? ''});
        })
    }

CodePudding user response:

It seems like the body property is a JSON string, so you'll need to parse it:

const items = JSON.parse(obj.body);

Then you can map over the items variable.

CodePudding user response:

{body: "Items":[{"key1":"value","key2":"value"},{"key1":"value","key2":"value"}],"Count":2,"ScannedCount":2}

This JSON file seems invalid.

  • Related