I need to convert a JSON array to a tab-delimited version so that I can save it as a .txt file so it can be uploaded on Mailchimp.
I would need result like this:
"Date","Pupil","Grade"
"25 May","Bloggs, Fred","C"
"25 May","Doe, Jane","B"
"15 July","Bloggs, Fred","A"
I'm not sure if whether this helps or not, but you can follow this structure and make any other small details to match your desired output ( I have no idea where should date and grade come from, but this is just an example ):
var json = '...your json string here...',
objects = JSON.parse( json ),
output = [],
finalString = '';
for ( let item in objects )
output.push([
new Date,
objects[ item ].lastName + ', ' + objects[ item ].firstName,
objects[ item ].gender
]);
Update:
You need to save each array inside of that output along a new line for your final string to save as .txt:
output.forEach( v => finalString += v.join( "\t" ) + "\n" )
Related
i want to convert a .csv file and write a new one. However I am not able to remove the first , i am kinda stuck here and it is driving me crazy.
This is my code:
var extractedtasks = tasks.slice(0, 3)
var extractedtasksformated = extractedtasks.toString().replace(/,$/g, "\n")
let csvformat = "EMAIL,PASSWORD,MAILBOX"
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksformated.replace(/,^/g,
""))
console.log(chalk.green("Successfully updated the CSV file"))
That's the output i am getting in the newly generated file
EMAIL,PASSWORD,MAILBOX
example1#gmail.com,Password123,example#gmail.com:password
,example2#gmail.com,Password123,example#gmail.com:password
,example3#gmail.com,Password123,example#gmail.com:password
Output extractedtasks:
[
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
Output extractedtasksformated:
,example3#gmail.com,Password123,example#gmail.com:passwordxample#gmail.com:password
Because extractedtasks is an array, instead of converting it to a string you should just join it with the expected separator:
extractedtasks = [
'example1#gmail.com,Password123,example#gmail.com:password\r',
'example2#gmail.com,Password123,example#gmail.com:password\r',
'example3#gmail.com,Password123,example#gmail.com:password\r'
]
extractedtasksJoined = extractedtasks.join("\n")
// "example1#gmail.com,Password123,example#gmail.com:password\r\nexample2#gmail.com..."
// depending on the target line separator, you should also probably
// remove the "\r"
extractedtasksJoined = extractedtasksJoined.replace("\r", "")
// finally
fs.writeFileSync(tasklocation[0], csvformat + "\n" + extractedtasksJoined + "\n")
I have a textbox which accepts user defined key value pairs like:
{'Apple':'Red', 'Lemon':'Green'} and i want it to be converted to an array of key value pair.
I have code:
var color= document.getElementById('txtColor').value;
The problem is i get it just as a string if i try: color['Apple'] it shows undefined; whereas i expect 'Red'. How can i do the conversion so that i get something like:
var color={'Apple':'Red', 'Lemon':'Green'}
and get value 'Red' on color['Apple'].
Thanks in advance.
I have a similar usecase. You have to JSON.parse() the value.
var obj = JSON.parse(document.getElementById('txtColor').value.replace(/'/g, '"'));
console.log(obj['Apple']);
<textarea id="txtColor">{'Apple':'Red', 'Lemon':'Green'}</textarea>
I assume following
let color = document.getElementById('txtColor').value; // This line returns {'Apple':'Red', 'Lemon':'Green'}
If I'm correct you can do following
try {
// Here you can write logic for format json ex. Convert single quotes to double quotes
// This may help to convert well formatted json string https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
let colorJson = JSON.parse(color);
console.log(colorJson["Apple"]) // This will return your expected value.
} catch(e) {
console.log('Invalid json format')
}
var color = document.getElementById('txtColor').value;
//JSON.stringify will validate the JSON string
var jsonValidString = JSON.stringify(eval("(" + color + ")"));
//If JSON string is valid then we can conver string to JSON object
var JSONObj = JSON.parse(jsonValidString);
//We can use JSON.KeyName or JSON["KeyName"] both way you can get value
console.log(JSONObj.Apple, " --- ", JSONObj["Apple"]);
console.log(JSONObj.Lemon, " --- ", JSONObj["Lemon"]);
<input id="txtColor" value="{'Apple':'Red', 'Lemon':'Green'}" type="text" />
I'm exporting json files to csv using Filesaver.js and json-export-excel.js. The comma separator is causing the columns to shift when it sees a comma in the string.
Plunker Demo
How can i ignore commas found within string?
<button ng-json-export-excel data="data" report-fields="{name: 'Name', quote: 'Quote'}" filename ="'famousQuote'" separator="," class="purple_btn btn">Export to Excel</button>
JS File:
$scope.data = [
{
name: "Jane Austen",
quote: "It isn\'t what we say or think that defines us, but what we do.",
},
{
name: "Stephen King",
quote: "Quiet people have the loudest minds.",
},
]
Current CSV output (Not Desired): (Note: | marks the columns in csv file)
Name Quote
Jane Austen | It isn't what we say or think that defines us| but what we do.|
Stephen King| Quiet people have the loudest minds. | |
Desired CSV output:
Name Quote
Jane Austen | It isn't what we say or think that defines us, but what we do.|
Stephen King| Quiet people have the loudest minds. |
For Excel, you need to wrap values in quotation marks. See this question.
In json-export-excel.js you'll see that the _objectToString method wraps the output in quotes but because the fieldValue variable isn't an object this is never called for this example.
function _objectToString(object) {
var output = '';
angular.forEach(object, function(value, key) {
output += key + ':' + value + ' ';
});
return '"' + output + '"';
}
var fieldValue = data !== null ? data : ' ';
if fieldValue !== undefined && angular.isObject(fieldValue)) {
fieldValue = _objectToString(fieldValue);
}
If you add an else statement to this to wrap the value in quotes, the CSV opens in Excel as desired.
} else if (typeof fieldValue === "string") {
fieldValue = '"' + fieldValue + '"';
}
Plunker
I've recently come across the term arbitrary data/ arbitrary json and i can't seem to understand what exactly is it and/or find any documentation on it. I know that JSON is a format for sending data over the internet, so how exactly can a format be arbitrary?
EDIT::
//more code
var buildItem = function(item) {
var title = item.name,
args = [],
output = '<li>';
if (item.type == 'method' || !item.type) {
if (item.signatures[0].params) {
$.each(item.signatures[0].params, function(index, val) {
args.push(val.name);
});
}
title = (/^jQuery|deferred/).test(title) ? title : '.' + title;
title += '(' + args.join(', ') + ')';
} else if (item.type == 'selector') {
title += ' selector';
}
output += '<h3>' + title + '</h3>';
output += '<div>' + item.desc + '</div>';
output += '</li>';
return output;
};
//more code
in the example code above, i am told that the .params is arbitrary data from a JSON request [for the jQuery API documentation].
What then is arbitrary data?
Would really appreciate any answers and/or clarifications.
jsFiddle: http://jsfiddle.net/QPR4Z/2/
Thanks!
arbitrary |ˈärbiˌtrerē|
adjective
based on random choice or personal whim, rather than any reason or
system: his mealtimes were entirely arbitrary.
Mathematics: (of a constant or other quantity) of unspecified value.
It just means there could be any value in there. This is opposed to a specification that says something like "this array always contains X, Y and Z". Arbitrary values in contrast say "we're sending you something in this array, but we can't really tell you in advance what exactly that is." If you're told that you can send arbitrary data yourself, it means you can send anything you want, it doesn't have to follow any particular format.
Note that this is all about the data contained in the JSON format, not about the JSON format itself.
It means "Some organisation of the data structure (including names of properties) that was just made up by some person" rather than being an established standard.
The data structure is arbitrary. It is expressed in the JSON standard (which isn't).
I'm trying to construct a String in JS that can be passed into JSON as an with a very particular format. Desired result is a string of the following form:
["PNG","350x150","127 KB"]
Where PNG correspond to a particular image's type, where 350x150 is the image's dimensions and where 127 KB is the image's size. Each of these threee values are string variables:
var imgType = getImageType(); // Returns "PNG"
var imgDim = getImageDim(); // Returns "350x150"
var imgSize = getImageSize(); // Returns "127 KB"
var imgDescription = '["' + imgType + '","' + imgDim + '","' + imgSize + '"]';
// Sanity check
alert(imgDescription);
iVO.images[thisImage] = {
"fizz":"buzz",
"imgDesc":imgDescription,
"foo":"bar"
}
alert(JSON.stringify(iVO));
The first alert (on the imgDescription variable) prints:
["PNG","350x150","127 KB"]
So far, so good. However, the minute we pass it to the iVO construct and stringify the resultant JSON, it generates the following output (after I pretty print format it):
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":"[\"PNG\",\"350x150\",\"127 KB\"]",
"foo":"bar"
}
}
}
All of my double quotes (") have been escaped (\")!!! Also, the value for imgDesc is enclosed in double-quotes, which is not what we want (see desired JSON below):
When I send this JSON back to the server its causing the server to choke.
Not sure what is going on here but I've tried several other suggestions, including replacing my double-quotes with '\x22' instances which didn't help.
Any ideas as to what would fix this to get the desired result from JSON.stringify(iVO)? Ultimately that's the only thing that matters, that the we end up sending the following to the server:
{
"images":
{
"4490i45"":
{
"fizz":"buzz",
"imgDesc":["PNG","350x150","127 KB"],
"foo":"bar"
}
}
}
No escaped double-quotes, and the value for imgDesc is not double-quoted. Thanks in advance!
Why don't you just put imgDescription as regular array
var imgDescription = [imgType , imgDim, imgSize];
Stringify should take care of what you are trying to do, otherwise you are passing imgDescription as a string and stringify would escape the quotes.
e.g.
var imgType = "PNG";
var imgDim = "350x150";
var imgSize = "127 KB";
var d = {
"fizz":"buzz",
"imgDesc":[imgType , imgDim, imgSize],
"foo":"bar"
}
console.log(JSON.stringify(d));
Output:
{"fizz":"buzz","imgDesc":["PNG","350x150","127 KB"],"foo":"bar"}