I want to output some fields into file using this query:
SELECT
CONCAT('[',
GROUP_CONCAT(
CONCAT(CHAR(13), CHAR(9), '{"name":"', name, '",'),
CONCAT('"id":', CAST(rid AS UNSIGNED), '}')
),
CHAR(13), ']')
AS json FROM `role`
INTO OUTFILE '/tmp/roles.json'
In output file I'm getting something like this:
[
\ {"name":"anonymous user","rid":1},
\ {"name":"authenticated user","rid":2},
\ {"name":"admin","rid":3},
\ {"name":"moderator","rid":4}
]
As you can see, newlines (char(13)
) has no backslashes, but tab characters (char(9)
) has. How can I get rid of them?
UPDATE Sundar G gave me a cue, so I modified the query to this:
SELECT
CONCAT('"name":', name),
CONCAT('"rid":', rid)
INTO outfile '/tmp/roles.json'
FIELDS TERMINATED BY ','
LINES STARTING BY '\t{' TERMINATED BY '},\n'
FROM `role`
I don't know why, but this syntax strips backslashes from output file:
{"name":"anonymous user","rid":1},
{"name":"authenticated user","rid":2},
{"name":"admin","rid":3},
{"name":"moderator","rid":4}
This is already pretty nice output, but I also would like to add opening and closing square brackets at the beginning and at the end of the file. Can I do this by means of MySQL syntax or I have to do that manually?
As described in
SELECT ... INTO
Syntax:That referenced page says:
and later explains:
Therefore, since you have not explicitly specifying a
FIELDS
clause, any occurrences of the defaultTERMINATED BY
character (i.e. tab) within a field will be escaped by the defaultESCAPED BY
character (i.e. backslash): so the tab character that you are creating gets so escaped. To avoid that, explicitly specify either a different field termination character or use the empty string as the escape character.However, you should also note that the size of your results will be limited by
group_concat_max_len
. Perhaps a better option would be:Try this query like
SELECT your_fields INTO outfile '/path/file' fields enclosed by '"' terminated by ',' lines terminated by '\n' FROM table;
hope this works..