gagle / node-properties

.properties parser/stringifier.
MIT License
133 stars 42 forks source link

Nested objects #19

Open alex-dow opened 9 years ago

alex-dow commented 9 years ago

Hello,

I have written code to convert a plain js object to a properties file, with support for nested objects and arrays. Its not perfect, but I feel that this is its own module rather than part of the project I'm working on.

Is there a plan to introduce this feature here? If so, o could prepare a pull request.

pixeldrew commented 7 years ago

Agree, if you're going to include 'namespace' support for parsing then it should be there for stringify.

mariomartinezricston commented 4 years ago

Any update about this issue ? I am unable to use this package due this issue:

`var properties = require ("properties");

var testObject = { "a": "1", "b": "2", "c": ["a", "b","$test","/test"], "db": { "host": "host", "pool": { "max": 15, "min": 1 } } }; var output = properties.stringify(testObject, {namespaces: true}); //namespace not doing anything

console.log(output);`

output:

$ node test.js a = 1 b = 2 c = a,b,$test,/test db = [object Object]

fatlard1993 commented 2 weeks ago

I needed to support something similar; simple arrays of strings and complex arrays of JSON objects. The solution wasn't immediately obvious to me from the docs, so I'm just sharing what I ended up going with incase it helps anyone that ends up here:

const jsonData = {
  integer: 6,
  string: '::1',
  boolean: true,
  simpleArray: ['x', 'y', 'z'],
  complexArray: [
    {
      integer: 6,
      string: '::1',
      boolean: true,
      object: {
        integer: 6,
        string: '::1',
        boolean: true,
      },
      array: ['x', 'y', 'z'],
    },
  ],
};

const dotProperties = `
  integer = 6
  string = ::1
  boolean = true
  simpleArray = x,y,z
  complexArray = [{"integer":6,"string":"::1","boolean":true,"object":{"integer":6,"string":"::1","boolean":true},"array":["x","y","z"]}]
`;

const simpleArrayKeys = new Set(['simpleArray', 'a', 'b', 'c']);
const complexArrayKeys = new Set(['complexArray', 'x', 'y', 'z']);

// JSON -> .properties
const replacer = (key, value) => complexArrayKeys.has(key) ? JSON.stringify(value) : value;

// .properties -> JSON
const reviver = (key, value) => {
  if (simpleArrayKeys.has(key)) return value.split(',');
  if (complexArrayKeys.has(key)) return JSON.parse(value);

  return value;
};

console.log(properties.stringify(jsonData, { replacer }));
console.log(properties.parse(dotProperties, { reviver }));