Jill Clover
Jill Clover

Reputation: 2328

Convert yaml to JSON returns ["object Object"]

I am building a backend service to convert YAML to JSON. However, it returns ["object Object"].

Postman post request in text: name: wf1

Code: import { safeLoad } from 'js-yaml'

app.post('/,
    function (req, res) {
        res.send(JSON.stringify(safeLoad(req.body)))
}
)

Return ["object Object"]

I expect it return JSON format of name: wf1.

Upvotes: 1

Views: 929

Answers (2)

eol
eol

Reputation: 24565

You need to make sure the body is actually parsed as raw text if you're intending to send text (i.e. Content-Type: text/plain) in your request. Using the text-function from body-parser should fix this issue:

app.use(bodyParser.text())
app.post('/', (req, res) => {
    res.send(JSON.stringify(safeLoad(req.body)));
})

Note that if you're intending to send actual json back to the client you need to change this to:

app.post('/', (req, res) => {
    res.json(safeLoad(req.body));
})

Upvotes: 1

Dylandy
Dylandy

Reputation: 181

First of all, according to js-yaml, safeLoad function only accept String as input type but req.body should return as a object. Maybe point to the particular key can work for you.

Upvotes: 0

Related Questions