I wrote a query that gives me posts from a table and also returns an info about each post's author:
SELECT post.id, post.text, post.datetime, JSON_OBJECT(
'username', user.username,
'firstName', user.firstName,
'firstName', user.lastName) as author
FROM post
INNER JOIN user ON post.authorId = user.id;
But in response the author field is a string:
author: "{"username": "@", "firstName": null}"
datetime: "2017-05-02T20:23:23.000Z"
id: 10
text: "5555"
I tried to fix that using CAST but anyway author is a string:
CAST(JSON_OBJECT(
'username', user.username,
'firstName', user.firstName,
'firstName', user.lastName) as JSON) as author
Why is it happened and how to fix that?
UPD:
I send the data from server using Node.js and Express:
app.get('/posts', (req, res, next) => {
getPosts().then((posts) => {
res.setHeader('Content-Type', 'application/json');
res.send(posts);
})
.catch(next);
});
// ...
getPosts() {
return new Promise((resolve, reject) => {
const query = `
SELECT post.id, post.text, post.datetime, JSON_OBJECT(
'username', user.username,
'firstName', user.firstName,
'firstName', user.lastName) as author
FROM post
INNER JOIN user ON post.authorId = user.id;`;
this.connection.query(query, (err, result) => {
if(err) {
return reject(new Error("An error occured getting the posts: " + err));
}
console.log(result) // prints author as a string
resolve(result || []);
});
});
}
Result of console.log:
{
id: 1,
text: 'hello, world!',
datetime: 2017-05-02T15:08:34.000Z,
author: '{"username": "@", "firstName": null}'
}
I also tried here change res.send(posts) to res.json(posts) but it's doesn't help.
My function from client that touch server for the posts:
export const getPosts = () => {
customFetch(apiUrl + '/posts')
.then(response => response.json())
.then(json => json)
};