I'm using D3.js to load csv file. It should look like this:
id,
a,
b,
But the csv is created inside my code, so I store it in a variable like this:
var flare = 'id,\na,\nb,\n'
However, the script does not work:
d3.csv(flare, function(error, data){
if(error) throw error;
});
How to solve the problem?
Depending on the version of D3 you are going to use, you have to choose the appropriate function:
v3.x
In versions 3.x d3.csv.parse() is what you are looking for:
Parses the specified string, which is the contents of a CSV file, returning an array of objects representing the parsed rows.
For your example this would be
var flare = 'id,\na,\nb,\n';
var data = d3.csv.parse(flare);
v4+
For version 4 and above the CSV parser has become part of the d3-dsv module. The function is now named d3.csvParse().
var flare = 'id,\na,\nb,\n';
var data = d3.csvParse(flare);
Related
I was trying to use the method found here (see most up-voted answer):
Google Apps Script Fastest way to find a row?
I currently use this while it does work I wanted to try the above linked method yet when I replace the below code
function AutoPopulate (evalue)
{
//uses google drive file irretator reads in JSON file and parses it to a Javascript object that we can work with
var iter = DriveApp.getFilesByName("units.json");
// iterate through all the files named units.json
while (iter.hasNext()) {
// define a File object variable and set the Media Tyep
var file = iter.next();
var jsonFile = file.getBlob().getDataAsString();
// log the contents of the file
//Logger.log(jsonFile);
}
var UnitDatabase = JSON.parse(jsonFile);
//Logger.log(UnitDatabase);
//Logger.log(UnitDatabase[1027]);
return UnitDatabase[evalue];
}
WITH THIS CODE:
function AutoPopulate (evalue)
{
//this method did not work for me but should have according to stackflow answer linked above I am trying to understand why or how I can find out why it may have thrown an error
var jsonFile = DriveApp.getFilesByName("units.json").next(),
UnitDatabase = UnitDatabase.getBlob().getDataAsString();
return UnitDatabase[evalue];
}
I get an error in the excecution indicating that there is a % at postion 0 in the JSON, between the methods I dont alter the JSON file in anyway so I dont understand why does the top method work but the bottom one does not?
For further information the idea behind the code is that I have a list of Unit numbers and model numbers that are in a spreadsheet. I then convert this to a JSON file, this however is only done when a new unit is added to the fleet. As I learned one can parse a whole JSON file into a javascript object which makes working with the data set much faster. This javascript object is used so that when a user enters a UNIT# the MODEL# is auto populated based on the JSON file.
I cannot share the JSON file as it contains client information.
Your code does not work for two reasons:
You have a typo in the line UnitDatabase = UnitDatabase.getBlob()... - it should be UnitDatabase = jsonFile.getBlob()...
If you want to retrieve a nested object from a json file - you need to parse the JSOn - otherwise it is considered a string and you can not access the nested structure
Modified working code:
function AutoPopulate2 (evalue)
{
var jsonFile = DriveApp.getFilesByName("units.json").next();
var UnitDatabase = JSON.parse(jsonFile.getBlob().getDataAsString());
return UnitDatabase[evalue];
}
Mind that this code will only work if you have a "units.json" file on your drive and if evalue is a valid 1st-level nested object of this json.
In my react project, I'm trying to convert XML data from an API call into JSON (using a library called xml-js).
As per the documentation, I'm importing the library in my parent component as follows
const convert = require('xml-js')
and then attempting the convert the API data as follows
const beerList =
'<Product>
<Name>Island Life IPA</Name>
<Volume>300ml/473ml</Volume>
<Price>$10/$13</Price>
<ABV>6.3%</ABV>
<Handpump>No</Handpump>
<Brewery>Eddyline</Brewery>
<IBU/>
<ABV>6.3%</ABV>
<Image>islandlife.png</Image>
<Country>New Zealand</Country>
<Description>Fruited IPA</Description>
<Pouring>Next</Pouring>
<IBU/>
<TapBadge/>
<Comments/>
</Product>'
const beerJs = convert(beerList,{compact: true, spaces: 4})
The errors are telling me that 'convert' is not a function, which tells me that the library isn't being imported. So is the issue with using 'require' syntax, and if so, what alternative would work in react?
which tells me that the library isn't imported
No. If that were the case, you wouldn't even get that far, your require call would throw an error.
Instead, it tells you that convert is not a function - which it isn't! Look at it in a debugger or log it, and you'll see it's an object with several functions inside. You can't call an object like a function.
Take a look at the xml-js docs again:
This library provides 4 functions: js2xml(), json2xml(), xml2js(), and xml2json(). Here are the usages for each one (see more details in the following sections):
var convert = require('xml-js');
result = convert.js2xml(js, options); // to convert javascript object to xml text
result = convert.json2xml(json, options); // to convert json text to xml text
result = convert.xml2js(xml, options); // to convert xml text to javascript object
result = convert.xml2json(xml, options); // to convert xml text to json text
So the solution is to call convert.xml2json and not convert:
const beerJs = convert.xml2json(beerList, {compact: true, spaces: 4})
Or maybe you want an actual object and not a JSON string, then you'd use convert.xml2js (in which case the spaces option is useless):
const beerJs = convert.xml2js(beerList, {compact: true})
I want to convert the following line of a file into JSON, I want to save that into an mongoose schema.
>HWI-ST700660_96:2:1101:1455:2154#5#0/1
GAA…..GAATG
Should be:
{“>HWI-ST700660_96:2:1101:1455:2154#5#0/1”: “GAA…..GAATG”}
I have tried several options, one sample below, but no success, any suggestion?
const parser = require("csv-parse/lib/sync");//import parser
const fs = require("fs");//import file reader
const path = require("path");//for join paths
const sourceData = fs.readFileSync(path.join(__dirname, "Reads.txt"), "utf8");//read the file, locally stored
console.log(sourceData);//print out for checking
const documents = parser(sourceData);//parsing, it works for other situations I have tested, in a column like data
console.log(documents);//printing out
This code give me an output as following:
[ [ '>HWI-ST700660_96:2:1101:1455:2154#5#0/1' ],
[ 'GAATGGAATGAAATGGATAGGAATGGAATGGAATGGAATGGATTGGAATGGATTAGAATGGATTGGAATGGAATGAAATTAATTTGATTGGAATGGAATG' ],...
Similar question: fasta file reading python
Because you are using the default config of the parser, it does simply output arrays of arrays in that configuration.
If you want to receive objects you will need to give the parser some options (columns) first. Take a look at the doc.
When using the sync parsing mode (like you are using) you can provide options like this:
const documents = parse(sourceData, {columns: true})
columns:true will infer the column names from the first line of the input csv.
The code above works however I would like to load the searchStrings array from a JSON file.
My goal is to have the json file on a shared drive so my coworkers are able to edit the names.
You can use following:
var someObject = require('./somefile.json')
JSON can be imported via require just like Node modules. (See Ben Nadel's explanation.)
You would generally want to store it as a global variable, rather than re-loading it on every keyup event. So if the JSON is saved as watchlist.json, you could add
var watchlist = require('./watchlist');
at the top of your code. Then the search command could be written (without needing the for loop) as:
kitten = kitten.toLowerCase();
if (watchlist.entities.indexOf(kitten) !== -1) {
alert('potential watchlist');
}
In the latest versions of Node you can simply use imports!
CommonJs:
const jsonContent = require('path/to/json/file.json')
ES6:
import jsonContent from 'path/to/json/file.json'
You can also import JSon files dinamically, take the following example:
if (condition) {
const jsonContent = require('path/to/json/file.json')
// Use JSon content as you prefer!
}
that way, you only load your JSon file if you really need it and your code will score better performances!
Do you prefer an old school approach?
ES6:
import fs from 'fs' // or const fs = require('fs') in CommonJs
const JSonFile = fs.readFileSync('path/to/json/file.json', 'utf8')
const toObject = JSON.parse(JSonFile)
// read properties from `toObject` constant!
Hope it helps :)
I am using CakePhp _serialize method to make a web service and show the data in JSON format.I used the .json extension at the end of the URL to show this data.Now i want to show this data in table.Output image is attached.Is this possible then how i can do it?
Thanks
The format is a bit odd. I would prefer something like: "task_list": [ .... ]; iterating over objects is always a bit tedious.
Here is the jQuery code:
var data = ...;
var items = data["task_list"];
var table = $('<table/>');
table.appendTo($('body'));
$.each(items, function(id, value) {
var tr = $('<tr/>');
table.append(tr);
$('<td/>').text(id).appendTo(tr);
$('<td/>').text(value).appendTo(tr);
});