0

Lets presume I am sending a POST request to /api/products. My body is like below

{
      "products":[
                {
                    "id":"5f5065e44a12bd00232bcc6g",
                    "status":"true"
                },
                {
                    "id":"5f5065e44a12bd00232bcc6g",
                    "status":"true"
                }
     ]
}

In my route I am trying to convert the above products to a JSON Object;

Below is my server code

const { products } = req.body;
console.log(JSON.parse(products));

but this gives me the error "message": "Something went wrong Unexpected token o in JSON at position 1"

How can i achieve this??

Cheers

Screenshots added

enter image description here

enter image description here

Tried below as well. But no luck

Nothing works.

const products = req.body;
console.dir(typeof products); // 'object'
console.dir(products); // { products: '[object Object]' } 

const { products } = req.body;
console.dir(typeof products); // 'string'
console.dir(products); // '[object Object]'

postman developer console is as below. Doesnt seem to be an issue

{
    "products":[
            {
                "id":"5f5065e44a12bd00232bcc6g",
                "status":"true"
            },
            {
                "id":"5f5065e44a12bd00232bcc6g",
                "status":"true"
            }
    ]
}
2
  • 5
    If that's your body, it's not valid JSON--you can't have a property key outside an object. (Is that the body?) Commented Sep 3, 2020 at 15:25
  • 2
    "In my route I am trying to convert the above products to a JSON Object;" JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. It sounds like you're trying to convert a string containing JSON to an object (not a JSON object, just an object). Commented Sep 3, 2020 at 15:27

5 Answers 5

1

It's not a JSON object, JSON objects are surrounded by curly braces.

if you return {"products": [ { "id":"5f5065e44a12bd00232bcc6g", "status":"true" }, { "id":"5f5065e44a12bd00232bcc6g", "status":"true" } ]}

then it will be worked.

Sign up to request clarification or add additional context in comments.

Comments

1

The best thing to do would be to fix what you're sending to /api/products by putting {} around it, like this:

{
    "products":[
            {
                "id":"5f5065e44a12bd00232bcc6g",
                "status":"true"
            },
            {
                "id":"5f5065e44a12bd00232bcc6g",
                "status":"true"
            }
    ]
}

Now it's valid JSON, and you can convert it via JSON.parse:

const obj = JSON.parse(req.body);
console.log(obj);
const { products } = obj;

or just

const { products } = JSON.parse(req.body);

Notice I'm using the entire body there. That will give you an object with a property (products) with the array of products. Alternatively, instead of parsing it manually, you could use middleware that would parse it automatically so that req.body is the parsed result, in which case it's just:

console.log(req.body);
const { products } = req.body;

If for some reason you can't send correct JSON, but it will always be in the form you've shown, you could add the {} afterward like this:

const obj = JSON.parse("{" + req.body + "}");
console.log(obj);
const { products } = obj;

or just

const { products } = JSON.parse("{" + req.body + "}");

but I strongly recommend not doing that, not least because you can't use middleware and sending malformed data around tends not to be ideal. Instead, send valid JSON in the first place.

6 Comments

I tried all your suggestions. But none of them work. i did console.log of my req.body and it shows below { product: '[object Object]' }. I am still wondering why this is not working
From that it sounds like the client-side code isn't sending what you've put in your question. Specifically, it sounds like the client-side code is manually creating a JSON string (never a good idea) and using string concatenation (+) with an object. When you do that, the object gets converted to "[object Object]" and added to the string.
In that case what is the best way as you think T.J? I have added some screenshots as well
Is it possible that some middleware is already converting the body from JSON? Using console.dir instead of console.log would reveal that.
@Alnitak - Indeed. As would a debugger.
|
1

Look at the content of your variable products, and your debugger.

In this line you're using an object destructuring assignment but the right hand side isn't an object, it's a string:

const { products } = req.body;

Try this instead:

const { products } = JSON.parse(req.body);

EDIT you appear to be using Express middleware or similar. There's a good chance that your object has already been converted from JSON so you just need your original line and not the JSON.parse line.

const { products } = req.body;
console.dir(products);

4 Comments

This seems much more on the right track, with the caveat that it's not 100% clear what's actually in the body.
@DaveNewton yup - that body really should have { .. } around it,
I have added json middleware from body-parser
@ShankaSomasiri right, so you shouldn't need to also JSON.parse the body yourself!
0

Figured it out.

Thanks to @T.j and @Alnitak was able to get this sorted. Used

let obj = req.body;

But i had an issue with my validator.

body('products')
      .trim()
      .not()
      .isEmpty()
      .withMessage('Custom product must have a main product'),

In the above code using .trim() converted the products into a string and once I removed the trim() it works perectly. Thanks all for the thoughts

Comments

-2

Try with JSON.stringify()

Otherwise, maybe you were declaring an object (const { products }), try without the {}

1 Comment

OP claims they have a string, stringifying it would be... redundant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.