save csv to array javascript - javascript

So im trying to join an array so i can save the string as csv.
It works but im getting extra quotes and columns showing up in the csv file, how do i fix my problem.
var arr = ["Merry, Christmas", "Halloween", "New Years", "other"]
var quotedAndCommaSeparated = "'" + arr.join("','") + "'";
After saving the string to a csv file, there is 2 problems.
There is 2 double quotes, one at the beginning and end of the line in csv.
The first string in array is also getting separated into 2 columns since it has a comma.

The CSV file format does not work well with single quote (') for this you can change your join string as follow.
var arr = ["Merry, Christmas", "Halloween", "New Years", "other"]
var quotedAndCommaSeparated = '"' + arr.join('","') + '"';
console.log(quotedAndCommaSeparated);

Per the spec for a CSV, you must use:
Double Quotes around each item, if they may contain double quotes or commas
Escape any double quotes within each item by "doubling" the double quotes
var arr = ["Merry, Christmas", "Halloween", "New Years", "Item with \"Double Quoted\" string"];
// Temporary array to store the modified entries in for the CSV
var arrDoubled = [];
// Loop over the original array, and double up the double quotes
// by taking each item in the `arr` array, and doing a global (`g`) replace
// to change all " to ""
arr.forEach(function(item) {
arrDoubled.push(item.replace(/"/g, '""'));
});
// Use Double Quotes instead of single for the CSV
// Note that '"' is the same as "\"" (each is a string with a single double quote as contents)
var quotedAndCommaSeparated = "\"" + arrDoubled.join("\",\"") + "\"";
console.log(quotedAndCommaSeparated);

Related

JSON.parse not creating a json object in javascript

I am getting below string from upstream. Have no control over it.
b"{'text': 'Airtel Tower (# BT Tower in Chasdmzoa, Delhi)', 'sentiment': '0.25'}"
I want to change the string to JSON. So the first thing I did was removing preceeding b'....' (upstream is a python program that produces utf-8 string as an output). So I am removing 'b' using substr..
str = msg.payload.substr(1);
Then I am trying to convert the string to JSON using JSON.stringify and JSON.parse.
console.log(typeof(str));
var t = JSON.stringify(str);
console.log(typeof(t));
var t = JSON.parse(t);
console.log("First: " + t);
var t = JSON.parse(t);
console.log("Second " + t);
x = t.text;
y = t["text"];
console.log(x + " ---- " + y);
Console Output:
string
string
First: "{'text': 'Airtel Tower(# KT Tower in Bang, Greater K
n), 'sentiment': '0.25'}"
Second {'text': 'Vodafone Tower (# LT Tower in Delhi, Greater K
), 'sentiment': '0.25'}
undefined ---- undefined
It fails to convert it to object even though JSON.stringify removed the extra quotes etc. and JSON.parse doesn't seem to work. What am I doing wrong?
const input = "b'\"{'text': 'Airtel Tower (# BT Tower in Chasdmzoa, Delhi)', 'sentiment': '0.25'}\"'";
const cleanString = str => str.split('"')[1].replace(/'/g, '"');
console.log(input);
// Result
console.log(JSON.parse(cleanString(input)));
Explanation
Split the string with the double quote " as a delimiter
Get the second item. This will give you {'text': 'Airtel Tower (# BT Tower in Chasdmzoa, Delhi)', 'sentiment': '0.25'}
Replace single quotes ' with double quotes ". This will give you {"text": "Airtel Tower (# BT Tower in Chasdmzoa, Delhi)", "sentiment": "0.25"}
Call JSON.parse on the previous string to have your object
There's an issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use ".
Simplest answer (for non-anti-eval-zealots):
var string = msg.payload.substring(3,msg.payload.length-2);
var t = eval("(" + string + ")");
If you can't stand, or can't use (strict mode?), eval, then you need to convert the single quotes to double quotes for parsing, as JSON only accepts double quotes:
var string = msg.payload.substring(3,msg.payload.length-2);
var t = JSON.parse(string.replace(/'/g, "\""));

How should a JSON string with quotes inside can be parsed with javascript

var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
Now JSON.parse(str) throws this error
Uncaught SyntaxError: Unexpected token M in JSON at position 43
Now replacing quotes escapes whole string and parsed JSON is not usable anymore
str = str.replace(/\\([\s\S])|(")/g,"\\$1$2");
"{\"Language\":\"en\",\"Type\":\"General\",\"Text\":\"\"Mela\" means \"apple\" in Italian\"}"
Other solutions like below do not seem to be working in this scenario
How to escape a JSON string containing newline characters using JavaScript?
You need to add a backslash before each double quote within your string as:
const str = '{"Language":"en","Type":"General","Text": "\\"Mela\\" means \\"apple\\" in Italian"}';
const obj = JSON.parse(str)
console.log(obj.Text)
In JSON you don't escape double quotes of the property name or the begging of the property value, just escape what's inside property value:
{\"Text\":\"\"Mela\" means ....
It should be like this:
{"Text":"\"Mela\" means ....
This can be done with multiple replacements:
var str = '{"Language":"en","Type":"General","Text":""Mela" means "apple" in Italian"}';
str = str.replace(/"/,"'"); //Replace all " with '
str = str.replace(/{'/,'{"') //Restore " to start of JSON
str = str.replace(/','/,'","'); //Restore " around JSON , separators
str = str.replace(/':'/,'":"'); //Restore " around JSON : separators
str = str.replace(/'}/,'"}'); //Restore " to end of JSON
str = str.replace(/'/,'\"'); //All remaining ' must be inside of data, so replace with properly escaped \"
console.log(str);
EDIT: A problem with this solution is that is will also replace original ' characters with " inside the text.

JSON Remove trailing comma from last object

This JSON data is being dynamically inserted into a template I'm working on. I'm trying to remove the trailing comma from the list of objects.
The CMS I'm working in uses Velocity, which I'm not too familiar with yet. So I was looking to write a snippet of JavaScript that detects that trailing comma on the last object (ITEM2) and removes it. Is there a REGEX I can use to detect any comma before that closing bracket?
[
{
"ITEM1":{
"names":[
"nameA"
]
}
},
{
"ITEM2":{
"names":[
"nameB",
"nameC"
]
}
}, // need to remove this comma!
]
You need to find ,, after which there is no any new attribute, object or array.
New attribute could start either with quotes (" or ') or with any word-character (\w).
New object could start only with character {.
New array could start only with character [.
New attribute, object or array could be placed after a bunch of space-like symbols (\s).
So, the regex will be like this:
const regex = /\,(?!\s*?[\{\[\"\'\w])/g;
Use it like this:
// javascript
const json = input.replace(regex, ''); // remove all trailing commas (`input` variable holds the erroneous JSON)
const data = JSON.parse(json); // build a new JSON object based on correct string
Try the first regex.
Another approach is to find every ,, after which there is a closing bracket.
Closing brackets in this case are } and ].
Again, closing brackets might be placed after a bunch of space-like symbols (\s).
Hence the regexp:
const regex = /\,(?=\s*?[\}\]])/g;
Usage is the same.
Try the second regex.
For your specific example, you can do a simple search/replace like this:
,\n]$
Replacement string:
\n]
Working demo
Code
var re = /,\n]$/;
var str = '[ \n { \n "ITEM1":{ \n "names":[ \n "nameA"\n ]\n }\n },\n { \n "ITEM2":{ \n "names":[ \n "nameB",\n "nameC"\n ]\n }\n },\n]';
var subst = '\n]';
var result = str.replace(re, subst);
Consider the Json input = [{"ITEM1":{"names":["nameA"]}},{"ITEM2":{"names":["nameB","nameC"]}},] without whitespaces.
I suggest a simple way using substring.
input = input.substring(0, input.length-2);
input = input + "]";
I developped a simple but useful logic for this purpose - you can try this.
Integer Cnt = 5;
String StrInput = "[";
for(int i=1; i<Cnt; i++){
StrInput +=" {"
+ " \"ITEM"+i+"\":{ "
+ " \"names\":["
+ " \"nameA\""
+ "]"
+"}";
if(i ==(Cnt-1)) {
StrInput += "}";
} else {
StrInput += "},";
}
}
StrInput +="]";
System.out.println(StrInput);

Parse string having key=value pairs as JSON

My node app receives a series of strings in the format "a=x b=y c=z" (i.e. a string containing several space-separated key=value pairs).
What is the neatest way of converting such a string into a JSON object of the form {a: x, b: y, c: z}?
I'm betting that there's a one-line solution, but haven't managed to find it yet.
Thanks.
One way would be to replace the with a , and an = with a ::
var jsonStr = '{' + str.replace(/ /g, ', ').replace(/=/g, ': ') + '}';
Or if you need quotes around the keys and values:
var jsonStr2 = '{"' + str.replace(/ /g, '", "').replace(/=/g, '": "') + '"}';
JSON.parse() it if you need.
Sample output:
str: a=x b=y c=z
jsonStr: {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
Building on John Bupit's excellent answer, I have made a couple of further enhancements to end up with the following (the string being parsed being in message):
var json = JSON.parse(('{"' + message.replace(/^\s+|\s+$/g,'').replace(/=(?=\s|$)/g, '="" ').replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, '", "').replace(/=/g, '": "') + '"}').replace(/""/g, '"'));
Basically the scheme is as follows:
First replace(): trim off any leading or trailing whitespace -- equivalent to trim()
Second replace(): add double quotes (empty string) for any value that is completely missing (e.g. key1= key2=val goes to key1="" key2=val).
Third replace(): replace each space (which acts as a delimiter) with ", ", but not where the space is within double quotes (i.e. part of a string value).
Fourth replace(): replace each = with ": "
Wrap the entire string up as follows: {"..."}
Finally, replace any double quotes "" created by the above steps (because the value string was already wrapped in quotes in message) with single quotes "
Even more finally, run JSON.parse() over the result.
The above scheme should cope with missing values, with some values being quoted and some unquoted, and with spaces within value strings, e.g. something like a= b="x" c="y y" d=z.
Assuming that you don't get nested objects in that format :
var sample = 'a=x b=y c=z';
var newobj = {};
sample.split(' ').forEach(function (value) {
var keypair = value.split('=');
newobj[keypair[0]] = keypair[1];
});
console.dir(newobj);
What this does is split on every white-space and push to an array, and the array is looped and each item in array is split again to get each key-value pair which is assigned to the newobj.
Here's a simple function that will do the trick
function stringToObj (string) {
var obj = {};
var stringArray = string.split(' ');
for(var i = 0; i < stringArray.length; i++){
var kvp = stringArray[i].split('=');
if(kvp[1]){
obj[kvp[0]] = kvp[1]
}
}
return obj;
}
newstr = ""
for kvp in #value.split(" ")
newstr += kvp.replace(/=/,'":"').replace(/^/, '"').replace(/$/, '"').replace(/\"\"/,'" "')
newstr = newstr.replace(/\"\"/g, '","')
jsn = JSON.parse('{' + newstr + '}')
I created a simple online tool for similar need: https://superal.github.io/online-tools/
Use cases:
To transfer key:value pairs copied from chrome network requests(form data or query string parameters) or postman headers key-value(in bulk edit style) to json format.
For example:
key:value pairs
platform:2
limit:10
start_time:1521561600
end_time:1522080000
offset:0
to json format
{
"platform": "2",
"limit": "10",
"start_time": "1521561600",
"end_time": "1522080000",
"offset": "0"
}
It can be parsed (converted to json) using the help of this npm athena-struct-parser package.
For more information about the package -- https://www.npmjs.com/package/athena-struct-parser
Sample Nodejs Code
var parseStruct =require('athena-struct-parser') ;
var str = '{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}'
var parseObj = parseStruct(str)
console.log(parseObj);
Sample string with key=value format taken
{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}
Result Parsed output
{
description: 'Check the Primary key count of TXN_EVENT table in Oracle',
datastore_order: '1',
zone: 'yellow',
aggregation_type: 'count',
updatedcount: '0',
updatedat: [ '2021-06-09T02:03:20.004Z' ]
}
I would use an approach leveraging URLSearchParams and Object.fromEntries() like so:
const input = "a=x b=y c=z";
const queryString = input.replaceAll(" ", "&");
const query = new URLSearchParams(queryString);
const output = Object.fromEntries(query);
console.log(output);
Breakdown:
The URLSearchParams constructor takes a string of key-value pairs joined by "&" as it's argument, and parses it into a URLSearchParams object instance. So to use this, the space separators in the original input need to be replaced with a "&" character.
The URLSearchParams instance we have after parsing is an iterable, so we can transform it into a plain Object with Object.fromEntries().
It's not too bad as a one-liner either:
const input = "a=x b=y c=z";
const output = Object.fromEntries(new URLSearchParams(input.replaceAll(" ", "&")));

How to write comma separated value in single quote in java script?

I have a dynamic list of emails which are separated by comma, and I want to put all in single comma
In example:
(a#zyz.com,b#xyz.com,c#xyz.com,d#xyz.com) to ('a#zyz.com','b#xyz.com','c#xyz.com','d#xyz.com')
I tried to resolve it, but didn't succeed.
Supposing you want to enclose emails with single quotes, you can split on , and then Array.map and then Array.join
var str = "a#zyz.com,b#xyz.com,c#xyz.com,d#xyz.com";
str = str.split(",").map(function(str){
return "'" + str + "'"; // add quotes
}).join(",") // join the array by a comma
use split method of javascript.
E.g.
var str = "a#zyz.com,b#xyz.com,c#xyz.com,d#xyz.com";
var res = str.split(',');

Categories

Resources