I have a JavaScript array:
cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
The cities.toString() function will give me
"LA, NYC, Riyadh, Frankfurt"
How do I get
"LA", "NYC", "Riyadh", "Frankfurt"
The simplest way I can think of is to use JSON.stringify and drop the first and last characters with slice, like this
var cities = ["LA", "NYC", "Riyadh", "Frankfurt"]
console.log(JSON.stringify(cities).slice(1, -1));
// "LA","NYC","Riyadh","Frankfurt"
If you want it, exactly like you mentioned in your answer, use map function to generate new Strings surrounded by double quotes and finally join them with , like this
console.log(cities.map(function (currentCity) {
return '"' + currentCity + '"';
}).join(', '));
// "LA", "NYC", "Riyadh", "Frankfurt"
If your actual strings will not have any , in them, then you can chain the split and join calls, like this
console.log(JSON.stringify(cities).slice(1, -1).split(",").join(", "));
// "LA", "NYC", "Riyadh", "Frankfurt"
You can use join function of array to join the array elements using any separator like:
var result = '"' + cities.join('", "') + '"' ;
Check the working demo fiddle
If you want to change an array into a string, there's array.join. It works well with whatever delimiter you want to use:
var array = ["LA", "NYC", "Riyadh", "Frankfurt"];
var string = '"' + array.join('", "') + '"';
// Result: "LA", "NYC", "Riyadh", "Frankfurt"
Related
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);
I need to give array of strings inside string.
my array will be ["2", "3"]
i += "{\"name\":\"" + args.Name + "\",\"values\":[\"" + value + "\"]
What I need:
"{"name":"category1",,"values":["1"]},{"name":"category2","values":["2","1"]
Actual output:
"{"name":"category1",,"values":["1"]},{"name":"category2","values":["2,1"]
The double quotes of values removing and make it as string array. How to achieve this?
Thanks in advance :)
Try to split your value by ,.
i += "{\"name\":\"" + args.Name + "\",\"values\":[\"" + value.split(',') + "\"]
// ----------------------------------------------------------^^^^^^^^^^^-------
try join() function of jQuery
var value = ["2","3"];
var output = "{\"name\":\"Test\",\"values\":[\"" + value.join('","')+ "\"]";
console.log(output);
So i'm trying to create a json string that looks like this:
{
"username": "John",
"email": "johndoe#gmail.com",
"address": "123 Fake St",
...
}
This is what I have:
stringPost += fieldName + ": " + fieldValue +", ";
And then I'm JSON.stringifying it. But it needs those necessary quotes. What I have returns like this:
"username: John, email: johndoe#gmail.com, address: 123 Fake St, "
// all in one wrapping quote: not what we need
I need it like this:
{"username": "john", "email": "johndoe#gmail.com"... // quotes with each value
I've tried adding the proper ' vs " quotes, but it just renders with \username... Help!
JSON.stringify takes an object as its parameter, not a string. Rather than using string concatenation, just create an object and set its keys to the fieldnames and values to the fieldvalues:
var jsonObj = {};
// now within some loop:
jsonObj[fieldName] = fieldValue;
// after the loop:
var ajaxString = JSON.stringify(jsonObj);
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(" ", "&")));
I have a JSON string: '{"place": {"address": "Main Street, \"The House\""}}'.
Before parsing it with JSON.parse() I have to make sure that the double quotes within double quotes are escaped properly.
I was trying to come up with the regex that would match "The House", but failed to so.
Any idea on how can I achieve desired result?
This would be possible with the help of positive lookahead assertion.
var s = '{"place": {"address": "Main Street, "The House""}}';
alert(s.replace(/"((?:"[^"]*"|[^"])*?)"(?=[:}])/g, function(m,group)
{
return '"' + group.replace(/"/g, '\\"') + '"'
}))
OR
var s = '{"place": {"address": "Main Street, "The House"", "country": "United Kingdom"}}';
alert(s.replace(/"((?:"[^"]*"|[^"])*?)"(?=[:},])(?=(?:"[^"]*"|[^"])*$)/gm, function(m,group)
{
return '"' + group.replace(/"/g, '\\"') + '"'
}))