Skip to content

How to specify flow level of a specific element? #613

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
njourdane opened this issue Mar 22, 2021 · 3 comments
Closed

How to specify flow level of a specific element? #613

njourdane opened this issue Mar 22, 2021 · 3 comments

Comments

@njourdane
Copy link

I have this data:

{
  "dict": [
    {
      "foo": [
        "bar"
      ]
    }
  ],
  "array": [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
  ]
}

And I would like dump it like this:

dict:
- foo:
  - bar
arrays:
- [1, 2, 3, 4, 5]
- [6, 7, 8, 9, 10]

Ie. indent all elements except array items.

I know I can use flowLevel to specify level of nesting, but how to apply it only for one item in data?

@rlidwka
Copy link
Member

rlidwka commented Apr 6, 2021

Not possible at the moment (unless you want to employ excessive amounts of hacking).

We can't add this option, because people are asking for dozens (if not hundreds) of these, and adding every one of them would bloat dumper API too much.

Any ideas for custom formatting perhaps?

@rlidwka
Copy link
Member

rlidwka commented Apr 6, 2021

closing as duplicate of #586

@rlidwka rlidwka closed this as completed Apr 6, 2021
@rlidwka
Copy link
Member

rlidwka commented Apr 6, 2021

just like in the ticket above, here's a hacky solution which you can use at your own risk:

const yaml = require('js-yaml');

function CustomDump(data, opts) {
  if (!(this instanceof CustomDump)) return new CustomDump(data, opts);
  this.data = data;
  this.opts = opts;
}

CustomDump.prototype.represent = function () {
  let result = yaml.dump(this.data, Object.assign({ replacer, schema, noArrayIndent: true }, this.opts));
  result = result.trim();
  if (result.includes('\n')) result = '\n' + result;
  return result;
}


let CustomDumpType = new yaml.Type('!format', {
  kind: 'scalar',
  resolve: () => false,
  instanceOf: CustomDump,
  represent: d => d.represent()
});


let schema = yaml.DEFAULT_SCHEMA.extend({ implicit: [ CustomDumpType ] });

function replacer(key, value) {
  if (key === '') return value; // top-level, don't change this
  if (Array.isArray(value) && value.length > 4) return CustomDump(value, { flowLevel: 0 });
  return value; // default
}

console.log(CustomDump(
{
  "dict": [
    {
      "foo": [
        "bar"
      ]
    }
  ],
  "array": [
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]
  ]
}
).represent().trim());

/* Returns:

dict:
- foo:
  - bar
array:
- [1, 2, 3, 4, 5]
- [6, 7, 8, 9, 10]
*/

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

No branches or pull requests

2 participants