Skip to content

add forceTextStrings option to give csv readers a hint to text fields#114

Open
patrickdk77 wants to merge 1 commit intokaue:masterfrom
patrickdk77:strings
Open

add forceTextStrings option to give csv readers a hint to text fields#114
patrickdk77 wants to merge 1 commit intokaue:masterfrom
patrickdk77:strings

Conversation

@patrickdk77
Copy link
Copy Markdown

Status

READY

Description

Quotes string fields so that when importing the csv, it can automatically detect text columns vs numeric columns.
This helps a lot with having working sort column on version numbers where 3.1 and 3.11 are not numbers but strings

@kaue
Copy link
Copy Markdown
Owner

kaue commented Jan 30, 2025

Hi @patrickdk77

Thanks a lot for this contribution! =)
But i think we already have good support for this use case using the typeHandlers options.

For example, you could write a handle function to convert all object types to string:

const jsonexport = require('jsonexport');

//data
const contacts = {
  'a' : Buffer.from('a2b', 'utf8'),
  'b' : Buffer.from('other field', 'utf8'),
  'x' : 22,
  'z' : function(){return 'bad ace'}
};

const convertToString = (anyObject) => String(anyObject)
const options = {
  //definitions to type cast
  typeHandlers: {
    Array: convertToString,
    Boolean: convertToString,
    Function: convertToString,
    Number: convertToString,
    String: convertToString,
    Buffer: convertToString,
  }
};

jsonexport(contacts, options, function(err, csv) {
  if (err) return console.error(err);
  console.log(csv);
});

This also gives more control, like only do this for Numbers.

Did you try using the typeHandlers? Do you agree its very similar to what forceTextStrings is implementing?

@kaue kaue self-assigned this Jan 30, 2025
@patrickdk77
Copy link
Copy Markdown
Author

i dont understand how this would enforce a text field ia quoted and a number field is not.

it can control the data in the field but i dont see how this xontrols the use of quotes for the field

@patrickdk77
Copy link
Copy Markdown
Author

If I am reading it right, the parseObject code reads the json and writes the csv values
It calls the typeHandler for each field that it reads in, so here the value could be modified
It then calls the escape function that adds the quotes aound the field if needed and escapes any quotes or newlines inside the field.
I dont see how typeHandler could adjust how the escape function works, since escape is called after the typeHandler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants