Reputation: 23
I need to export string to csv.
Example of a string:
[{"name":"ALIASED_LINE_WIDTH_RANGE","value":{"0":1,"1":1}}]
I want to keep commas inside the string as commas not as separator.
So I want to keep this string as 1 element. I tried to wrap it with quotes "" but it doesn't work. I want the same output, so I want the string:
[{"name":"ALIASED_LINE_WIDTH_RANGE","value":{"0":1,"1":1}}]
But I want commas not to be considered as separators.
Upvotes: 1
Views: 1466
Reputation: 24952
"
) in your current string must be replaced with two double quotes (""
)"...
").Given your example string:
[{"name":"ALIASED_LINE_WIDTH_RANGE","value":{"0":1,"1":1}}]
This is how it must be formatted in the resultant CSV file:
"[{""name"":""ALIASED_LINE_WIDTH_RANGE"",""value"":{""0"":1,""1"":1}}]"
^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
Note In the example above the necessary additional double quotes ("
) are indicated by the caret symbols (^
).
(The caret symbols exist for illustrative purposes only)
Consider the following two examples when declaring your CSV string in JavaScript:
Example A: If your JavaScript coding style typically uses single quotes ('
) simply encase the preceding CSV formatted string within single quotes ('...'
).
For example:
const str = '"[{""name"":""ALIASED_LINE_WIDTH_RANGE"",""value"":{""0"":1,""1"":1}}]"';
// ^ ^
console.log(str);
Example B: However, If your JavaScript coding style typically uses double quotes ("
) then:
"..."
)\
).For example:
const str = "\"[{\"\"name\"\":\"\"ALIASED_LINE_WIDTH_RANGE\"\",\"\"value\"\":{\"\"0\"\":1,\"\"1\"\":1}}]\"";
// ^^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
console.log(str);
Note: As you can see, Example A is terse compared to Example B, however when running either of the two preceding code snippets the string logged to the console is essentially the same. They both produce the desired CSV formatted string.
If the string that you've provided in your question is derived by utilizing the JSON.stringify()
method to convert a JavaScript array of object(s) to a JSON string. Then you may want to consider the following:
const input = [{
name: 'ALIASED_LINE_WIDTH_RANGE',
value: {
0: 1,
1: 1
}
}];
const str = `"${JSON.stringify(input).replace(/"/g, '""')}"`;
console.log(str)
As you can see, if you run the preceding code snippet, it also logs to the console the desired CSV formatted string. It does this by utilizing:
JSON.stringify()
method to convert the input
value to a JSON string.replace()
method replaces all double quotes ("
) with two double quotes (""
)."..."
) we utilize a Template Literal.Upvotes: 1