Skip to content

fix(stringify): emit root-level keys before sections - #40

Open
mahirhir wants to merge 1 commit into
Sdju:masterfrom
mahirhir:fix-stringify-root-keys
Open

fix(stringify): emit root-level keys before sections#40
mahirhir wants to merge 1 commit into
Sdju:masterfrom
mahirhir:fix-stringify-root-keys

Conversation

@mahirhir

Copy link
Copy Markdown

Problem

stringify writes object keys in their original order, so a root-level key that comes after a nested object is written underneath that object's [section] header. When the output is read back with parse, the root key is absorbed into the section instead of staying at the top level, so parse(stringify(obj)) does not return obj:

import { parse, stringify } from 'js-ini';

const obj = { section: { inner: 'a' }, root: 'b' };

stringify(obj);
// "\n[section]\ninner=a\nroot=b"

parse(stringify(obj), { autoTyping: false });
// { section: { inner: 'a', root: 'b' } }   <-- "root" moved into [section]

Cause

In an INI document every key after a [section] header belongs to that section, so root-level keys can only be represented before the first section. stringify iterates Object.keys(data) in insertion order, which can place a root key after a section that was declared earlier in the object.

Fix

Order the top-level keys so non-object (scalar) keys are written before any object/array section. Relative order within each group is preserved, and output is unchanged for objects that already list their root keys first, so the existing fixtures and tests are unaffected. Added a test for the round trip.

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.

1 participant