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.
CodePudding user response:
How the string must be formatted in the resultant CSV file.
- All double quotes (
"
) in your current string must be replaced with two double quotes (""
) - The whole string must then be encased within 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)
Declaring the string in JS.
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:
Example B: However, If your JavaScript coding style typically uses double quotes ("
) then:
- Encase the CSV formatted string within double quotes (
"..."
) - Also, escape all interior double quotes with a backslash (
\
).
For example:
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.
Additional note.
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:
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:
- The
JSON.stringify()
method to convert theinput
value to a JSON string. - Subsequently the String's
replace()
method replaces all double quotes ("
) with two double quotes (""
). - To encase the whole resultant string within double quotes (
"..."
) we utilize a Template Literal.