flattify 1.0.2 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/path.d.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { _ as Notation, a as ContainersOf, c as FlattenOptions, d as TupleEntries, f as TypeDepthLimit, h as Option, i as Below, l as Join, m as IsUnion, n as Segments, o as Context, p as IsAny, s as Flatten, t as PathContext, u as Kind } from "./path-types-BjuDIcLg.js";
2
+ //#region src/path/types.d.ts
3
+ /** How the paths given to the `flattify/path` helpers are written. */
4
+ interface PathOptions {
5
+ /** Separates the keys of a path. Default: `'.'`. */
6
+ delimiter?: string;
7
+ /** `'dot'` (`items.0.id`), `'bracket'` (`items[0].id`) or `'pointer'` (`/items/0/id`, RFC 6901). Default: `'dot'`. */
8
+ notation?: Notation;
9
+ /** Reads `\` as an escape, so `'a\\.b'` is the single key `'a.b'`. Default: `true`. */
10
+ escape?: boolean;
11
+ }
12
+ /** Options of `set`: how the path is written, and what is created for missing keys. */
13
+ interface SetOptions extends PathOptions {
14
+ /** Creates objects only, never arrays, for missing keys along the path. Default: `false`. */
15
+ object?: boolean;
16
+ /** Largest index that creates an array for a missing key; larger ones create an object. Default: `1000`. */
17
+ arrayLimit?: number;
18
+ }
19
+ type ContextOf$1<O> = {
20
+ delimiter: Option<O, "delimiter", ".">;
21
+ notation: Option<O, "notation", "dot">;
22
+ escape: Option<O, "escape", true>;
23
+ maxDepth: undefined;
24
+ safe: false;
25
+ keepEmpty: true;
26
+ };
27
+ type IsWide<C extends Context> = string extends C["delimiter"] ? true : IsUnion<C["notation"]> extends true ? true : boolean extends C["escape"] ? true : false;
28
+ type PathsOf<T, P extends string, D extends unknown[], C extends Context> = T extends readonly unknown[] ? number extends T["length"] ? Node<T[number], Join<P, `${number}`, true, D, C>, D, C> : Entries<TupleEntries<T>, P, true, D, C> : Entries<T, P, false, D, C>;
29
+ type Entries<T, P extends string, IsArray extends boolean, D extends unknown[], C extends Context> = { [K in keyof T]-?: K extends string | number ? Node<T[K], Join<P, K, IsArray, D, C>, D, C> : never; }[keyof T];
30
+ type Node<V, K extends string, D extends unknown[], C extends Context> = IsAny<V> extends true ? K | Below<K, C> : K | (D["length"] extends TypeDepthLimit ? Below<K, C> : Nested<ContainersOf<V, C>, K, D, C>);
31
+ type Nested<V, K extends string, D extends unknown[], C extends Context> = V extends unknown ? (Kind<V, C> extends "unknown" ? Below<K, C> : [PathsOf<V, K, [...D, unknown], C>] extends [infer Paths] ? Paths : never) : never;
32
+ /**
33
+ * Every path of `T`, to an object, an array or a value: what `get`, `set`, `has` and `del` accept.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * type P = Path<{ user: { tags: string[] } }>;
38
+ * // 'user' | 'user.tags' | `user.tags.${number}`
39
+ * ```
40
+ */
41
+ type Path<T, O extends PathOptions = {}> = IsAny<T> extends true ? string : IsWide<ContextOf$1<O>> extends true ? string : T extends unknown ? ([PathsOf<T, "", [], ContextOf$1<O>>] extends [infer Paths extends string] ? Paths : never) : never;
42
+ /** One step of `Walk`. `Get` is `true` when reading, where arrays and records may miss the key. */
43
+ type Step<T, K extends string, Get extends boolean> = T extends unknown ? IsAny<T> extends true ? any : unknown extends T ? unknown : T extends null | undefined ? undefined : T extends readonly unknown[] ? number extends T["length"] ? K extends `${number}` ? T[number] | (Get extends true ? undefined : never) : undefined : K extends keyof T ? T[K] : undefined : [keyof T] extends [never] ? unknown : K extends keyof T ? T[K] | (string extends keyof T ? (Get extends true ? undefined : never) : never) : K extends `${infer N extends number}` ? N extends keyof T ? T[N] : IndexValue<T, Get> : IndexValue<T, Get> : never;
44
+ type IndexValue<T, Get extends boolean> = string extends keyof T ? T[string & keyof T] | (Get extends true ? undefined : never) : undefined;
45
+ type Walk<T, S, Get extends boolean> = S extends [infer K extends string, ...infer Rest] ? Walk<Step<T, K, Get>, Rest, Get> : S extends [] ? T : unknown;
46
+ /**
47
+ * The value at path `P` of `T`. Array elements and record values may be missing, so they include
48
+ * `undefined`, as with `noUncheckedIndexedAccess`.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * type City = Get<{ user: { address: { city: string } } }, 'user.address.city'>; // string
53
+ * type Tag = Get<{ tags: string[] }, 'tags.0'>; // string | undefined
54
+ * ```
55
+ */
56
+ type Get<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, true> : never;
57
+ /** The type `set` accepts at path `P` of `T`. */
58
+ type SetValue<T, P extends string, O extends PathOptions = {}> = IsAny<T> extends true ? any : string extends P ? unknown : IsWide<ContextOf$1<O>> extends true ? unknown : [Segments<P, ContextOf$1<O>>] extends [infer S] ? Walk<T, S, false> : never;
59
+ //#endregion
60
+ //#region src/path/path.d.ts
61
+ /**
62
+ * Reads the value at `path`, or `undefined` when a key is missing along the way. The JSON Pointer `''`
63
+ * is `obj` itself.
64
+ *
65
+ * The path is autocompleted and the result typed from `obj`. Plain objects and arrays are read through
66
+ * their own keys only: `get({}, 'constructor')` is `undefined`.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { get } from 'flattify/path';
71
+ *
72
+ * const order = { items: [{ sku: 'A1', qty: 2 }] };
73
+ * get(order, 'items.0.sku'); // 'A1', typed string | undefined
74
+ * get(order, '/items/0/qty', { notation: 'pointer' }); // 2
75
+ * ```
76
+ */
77
+ export declare function get<T extends object, P extends Path<T>>(obj: T, path: P): Get<T, P>;
78
+ /**
79
+ * Reads the value at `path`, written in another `delimiter` or `notation`.
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * get(order, '/items/0/sku', { notation: 'pointer' }); // 'BOOK-1'
84
+ * ```
85
+ */
86
+ export declare function get<T extends object, P extends Path<T, O>, const O extends PathOptions>(obj: T, path: P, options: O): Get<T, P, O>;
87
+ /**
88
+ * Reads the value at a path only known at runtime, such as one coming from user input: the result is
89
+ * `unknown`.
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * const value = get(data, error.instancePath, { notation: 'pointer' }); // unknown
94
+ * ```
95
+ */
96
+ export declare function get(obj: object, path: string, options?: PathOptions): unknown;
97
+ /**
98
+ * `true` when every key of `path` exists, even if the value there is `undefined`.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * has({ a: { b: undefined } }, 'a.b'); // true
103
+ * has({ a: {} }, 'a.b'); // false
104
+ * ```
105
+ */
106
+ export declare function has<T extends object, O extends PathOptions = {}>(obj: T, path: Path<T, O> | (string & {}), options?: O): boolean;
107
+ /**
108
+ * Sets the value at `path`, creating the missing objects (or arrays, for index keys) along the way, and
109
+ * returns `obj`, which is modified. The value is type-checked against the path.
110
+ *
111
+ * Paths with a `__proto__` segment are ignored; other keys are only ever created as own properties, so
112
+ * no path reaches `Object.prototype`.
113
+ *
114
+ * @example
115
+ * ```ts
116
+ * import { set } from 'flattify/path';
117
+ *
118
+ * const config: { db: { port: number } } = { db: { port: 5432 } };
119
+ * set(config, 'db.port', 6543);
120
+ * set(config, 'db.port', '6543'); // type error: string is not number
121
+ * ```
122
+ */
123
+ export declare function set<T extends object, P extends Path<T>>(obj: T, path: P, value: SetValue<T, P>): T;
124
+ /**
125
+ * Sets the value at `path`, written in another `delimiter` or `notation`, or with `object` and
126
+ * `arrayLimit` to choose what is created for missing keys.
127
+ *
128
+ * @example
129
+ * ```ts
130
+ * set(config, 'db__port', 6543, { delimiter: '__' });
131
+ * ```
132
+ */
133
+ export declare function set<T extends object, P extends Path<T, O>, const O extends SetOptions>(obj: T, path: P, value: SetValue<T, P, O>, options: O): T;
134
+ /**
135
+ * Deletes the key at `path` and returns `true`, or `false` when there was nothing to delete. Array
136
+ * elements are deleted in place, leaving a hole, as `delete` does.
137
+ *
138
+ * @example
139
+ * ```ts
140
+ * const user = { name: 'Ada', password: 'secret' };
141
+ * del(user, 'password'); // true, user is { name: 'Ada' }
142
+ * ```
143
+ */
144
+ export declare function del<T extends object, O extends PathOptions = {}>(obj: T, path: Path<T, O> | (string & {}), options?: O): boolean;
145
+ /**
146
+ * The path of every value `flatten` would produce, in the same order.
147
+ *
148
+ * @example
149
+ * ```ts
150
+ * paths({ user: { name: 'Ada', tags: ['admin'] } });
151
+ * // ['user.name', 'user.tags.0']
152
+ * ```
153
+ */
154
+ export declare function paths<T extends object>(obj: T): Extract<keyof Flatten<T>, string>[];
155
+ /**
156
+ * The paths `flatten(obj, options)` produces, with the same options.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * paths({ user: { tags: ['admin'] } }, { notation: 'bracket' }); // ['user.tags[0]']
161
+ * ```
162
+ */
163
+ export declare function paths<T extends object, const O extends FlattenOptions>(obj: T, options: O): Extract<keyof Flatten<T, O>, string>[];
164
+ type ContextOf<O> = {
165
+ delimiter: Option<O, "delimiter", ".">;
166
+ notation: Option<O, "notation", "dot">;
167
+ escape: Option<O, "escape", true>;
168
+ };
169
+ type ParsedPath<P extends string, O> = string extends P ? string[] : ContextOf<O> extends (infer C extends PathContext) ? (string extends C["delimiter"] ? string[] : Segments<P, C>) : string[];
170
+ /**
171
+ * Splits a path into its keys, reading escapes and brackets.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * parsePath('user.tags.0'); // ['user', 'tags', '0']
176
+ * parsePath('a\\.b.c'); // ['a.b', 'c']
177
+ * parsePath('items[0][id]', { notation: 'bracket' }); // ['items', '0', 'id']
178
+ * ```
179
+ */
180
+ export declare function parsePath<const P extends string, const O extends PathOptions = {}>(path: P, options?: O): ParsedPath<P, O>;
181
+ /**
182
+ * Joins keys into a path, escaping them when needed: the reverse of `parsePath`. In bracket notation,
183
+ * keys that are array indices are written between brackets.
184
+ *
185
+ * @example
186
+ * ```ts
187
+ * stringifyPath(['user', 'first.name']); // 'user.first\\.name'
188
+ * stringifyPath(['items', '0', 'id'], { notation: 'bracket' }); // 'items[0].id'
189
+ * stringifyPath(['a/b', 'c'], { notation: 'pointer' }); // '/a~1b/c'
190
+ * ```
191
+ */
192
+ export declare function stringifyPath(keys: readonly (string | number)[], options?: PathOptions): string;
193
+ /**
194
+ * Escapes a single key so it can be put in a path as it is.
195
+ *
196
+ * @example
197
+ * ```ts
198
+ * `user.${escapeKey('first.name')}`; // 'user.first\\.name'
199
+ * escapeKey('a/b', { notation: 'pointer' }); // 'a~1b'
200
+ * ```
201
+ */
202
+ export declare function escapeKey(key: string, options?: PathOptions): string;
203
+ //#endregion
204
+ export type { Get, Notation, Path, PathOptions, SetOptions, SetValue };
package/dist/path.js ADDED
@@ -0,0 +1,124 @@
1
+ import { a as escapeKey$1, c as assign, i as validateNotation, n as validate, o as escapePointer, r as pathFormat, s as isIndex, t as flatten, u as isPlainObject } from "./flatten-CYe7gyYE.js";
2
+ //#region src/path/path.ts
3
+ const MISSING = Symbol("missing");
4
+ const FORBIDDEN = /* @__PURE__ */ new Set([
5
+ "__proto__",
6
+ "constructor",
7
+ "prototype"
8
+ ]);
9
+ const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
10
+ const isTraversable = (value) => typeof value === "object" && value !== null || typeof value === "function";
11
+ function formatOf(options) {
12
+ const { delimiter = ".", notation = "dot", escape = true } = options;
13
+ validateNotation(notation);
14
+ if (notation !== "pointer") validate(delimiter, escape);
15
+ return pathFormat(notation, delimiter, escape);
16
+ }
17
+ /**
18
+ * Reads `key` of `target`. Plain objects and arrays expose their own keys only, so `'toString'` or
19
+ * `'constructor'` are missing on data; other objects (class instances, dates...) expose inherited
20
+ * properties too, except `__proto__`, `constructor` and `prototype`.
21
+ */
22
+ function read(target, key) {
23
+ if (isPlainObject(target) || Array.isArray(target)) return hasOwn(target, key) ? target[key] : MISSING;
24
+ if (FORBIDDEN.has(key) && !hasOwn(target, key)) return MISSING;
25
+ return key in target ? target[key] : MISSING;
26
+ }
27
+ function checkTarget(input, name) {
28
+ if (!isTraversable(input)) throw new TypeError(`${name}() expects an object or an array`);
29
+ }
30
+ function get(obj, path, options = {}) {
31
+ checkTarget(obj, "get");
32
+ let current = obj;
33
+ for (const key of formatOf(options).split(path)) {
34
+ if (!isTraversable(current)) return void 0;
35
+ current = read(current, key);
36
+ if (current === MISSING) return void 0;
37
+ }
38
+ return current;
39
+ }
40
+ function has(obj, path, options = {}) {
41
+ checkTarget(obj, "has");
42
+ let current = obj;
43
+ for (const key of formatOf(options).split(path)) {
44
+ if (!isTraversable(current)) return false;
45
+ current = read(current, key);
46
+ if (current === MISSING) return false;
47
+ }
48
+ return true;
49
+ }
50
+ function set(obj, path, value, options = {}) {
51
+ checkTarget(obj, "set");
52
+ const { object = false, arrayLimit = 1e3 } = options;
53
+ if (arrayLimit !== Infinity && (!Number.isInteger(arrayLimit) || arrayLimit < 0)) throw new RangeError("`arrayLimit` must be a non-negative integer or Infinity");
54
+ const segments = formatOf(options).split(path);
55
+ if (segments.length === 0) throw new TypeError("set() cannot replace the whole object: the JSON Pointer \"\" has no key");
56
+ if (segments.includes("__proto__")) return obj;
57
+ let target = obj;
58
+ for (let i = 0; i < segments.length - 1; i++) {
59
+ const child = read(target, segments[i]);
60
+ if (isTraversable(child)) target = child;
61
+ else {
62
+ const next = !object && isIndex(segments[i + 1], arrayLimit) ? [] : {};
63
+ assign(target, segments[i], next);
64
+ target = next;
65
+ }
66
+ }
67
+ assign(target, segments[segments.length - 1], value);
68
+ return obj;
69
+ }
70
+ function del(obj, path, options = {}) {
71
+ checkTarget(obj, "del");
72
+ const segments = formatOf(options).split(path);
73
+ if (segments.length === 0) return false;
74
+ let target = obj;
75
+ for (let i = 0; i < segments.length - 1; i++) {
76
+ if (!isTraversable(target)) return false;
77
+ target = read(target, segments[i]);
78
+ }
79
+ const last = segments[segments.length - 1];
80
+ if (!isTraversable(target) || !hasOwn(target, last)) return false;
81
+ return delete target[last];
82
+ }
83
+ function paths(obj, options = {}) {
84
+ return Object.keys(flatten(obj, options));
85
+ }
86
+ function parsePath(path, options = {}) {
87
+ return formatOf(options).split(path);
88
+ }
89
+ /**
90
+ * Joins keys into a path, escaping them when needed: the reverse of `parsePath`. In bracket notation,
91
+ * keys that are array indices are written between brackets.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * stringifyPath(['user', 'first.name']); // 'user.first\\.name'
96
+ * stringifyPath(['items', '0', 'id'], { notation: 'bracket' }); // 'items[0].id'
97
+ * stringifyPath(['a/b', 'c'], { notation: 'pointer' }); // '/a~1b/c'
98
+ * ```
99
+ */
100
+ function stringifyPath(keys, options = {}) {
101
+ var _path;
102
+ const format = formatOf(options);
103
+ const bracket = options.notation === "bracket";
104
+ let path;
105
+ for (const key of keys) path = format.join(path, String(key), bracket && isIndex(String(key), Infinity));
106
+ return (_path = path) !== null && _path !== void 0 ? _path : "";
107
+ }
108
+ /**
109
+ * Escapes a single key so it can be put in a path as it is.
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * `user.${escapeKey('first.name')}`; // 'user.first\\.name'
114
+ * escapeKey('a/b', { notation: 'pointer' }); // 'a~1b'
115
+ * ```
116
+ */
117
+ function escapeKey(key, options = {}) {
118
+ const { delimiter = ".", notation = "dot" } = options;
119
+ formatOf(options);
120
+ if (notation === "pointer") return escapePointer(key);
121
+ return escapeKey$1(key, delimiter, notation === "bracket" ? "[" : "");
122
+ }
123
+ //#endregion
124
+ export { del, escapeKey, get, has, parsePath, paths, set, stringifyPath };
package/package.json CHANGED
@@ -1,28 +1,117 @@
1
1
  {
2
2
  "name": "flattify",
3
- "version": "1.0.2",
4
- "description": "Convert JSON to \"Flat JSON\"",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "./node_modules/mocha/bin/mocha --reporter spec ./test/flattify.js"
3
+ "version": "2.0.1",
4
+ "description": "Flatten and unflatten nested objects without losing data: dates, nulls, empty objects and dotted keys survive the round trip. Typed paths, safe on untrusted input, zero dependencies.",
5
+ "author": "Fernando Machado Bernardino <fernandombernardino@gmail.com>",
6
+ "homepage": "https://github.com/NandoMB/flattify#readme",
7
+ "type": "module",
8
+ "license": "MIT",
9
+ "packageManager": "pnpm@12.5.1",
10
+ "bugs": {
11
+ "url": "https://github.com/NandoMB/flattify/issues"
8
12
  },
9
13
  "repository": {
10
14
  "type": "git",
11
15
  "url": "git+https://github.com/NandoMB/flattify.git"
12
16
  },
13
- "keywords": [
14
- "JSON",
15
- "flat",
16
- "plain"
17
+ "publishConfig": {
18
+ "access": "public",
19
+ "provenance": true
20
+ },
21
+ "sideEffects": false,
22
+ "main": "./dist/index.cjs",
23
+ "module": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "require": {
32
+ "types": "./dist/index.d.cts",
33
+ "default": "./dist/index.cjs"
34
+ }
35
+ },
36
+ "./path": {
37
+ "import": {
38
+ "types": "./dist/path.d.ts",
39
+ "default": "./dist/path.js"
40
+ },
41
+ "require": {
42
+ "types": "./dist/path.d.cts",
43
+ "default": "./dist/path.cjs"
44
+ }
45
+ },
46
+ "./package.json": "./package.json"
47
+ },
48
+ "files": [
49
+ "dist",
50
+ "path"
17
51
  ],
18
- "author": "Fernando Machado Bernardino <fernandombernardino@gmail.com>",
19
- "license": "MIT",
20
- "bugs": {
21
- "url": "https://github.com/NandoMB/flattify/issues"
52
+ "scripts": {
53
+ "dev": "vitest --project node",
54
+ "test": "vitest run --project node",
55
+ "coverage": "vitest run --project node --coverage",
56
+ "bench": "pnpm run build && vitest bench --run --config bench/vitest.config.mts",
57
+ "claims": "pnpm run build && tsc -p bench && vitest run --config bench/vitest.config.mts",
58
+ "size": "pnpm run build && node bench/size.js",
59
+ "build": "tsdown",
60
+ "lint": "tsc",
61
+ "ci": "pnpm run lint && pnpm run test && pnpm run build && pnpm run lint:package",
62
+ "release": "node scripts/release.js",
63
+ "changeset:version": "changeset version && node scripts/sync-jsr-version.js",
64
+ "lint:package": "publint && attw --pack .",
65
+ "test:browser": "vitest run --project browser",
66
+ "test:bun": "bunx --bun vitest run --project node",
67
+ "test:deno": "deno run -A node_modules/vitest/vitest.mjs run --project node",
68
+ "test:workers": "node test/workers/run.js",
69
+ "test:ts-legacy": "node node_modules/typescript-5.0/bin/tsc -p test/typescript-5.0",
70
+ "lint:jsr": "deno publish --dry-run --allow-dirty",
71
+ "test:ci": "pnpm run ci && pnpm run test:ts-legacy && pnpm run test:workers && pnpm run test:browser && pnpm run test:bun && pnpm run test:deno && pnpm run lint:jsr"
22
72
  },
23
- "homepage": "https://github.com/NandoMB/flattify#readme",
24
73
  "devDependencies": {
25
- "chai": "^3.5.0",
26
- "mocha": "^2.4.5"
27
- }
74
+ "@arethetypeswrong/cli": "^0.18.5",
75
+ "@changesets/cli": "^3.0.3",
76
+ "@types/node": "^26.6.2",
77
+ "@vitest/browser-playwright": "^5.0.1",
78
+ "@vitest/coverage-istanbul": "^5.0.1",
79
+ "es-toolkit": "1.52.0",
80
+ "esbuild": "^0.28.2",
81
+ "fast-check": "^4.10.2",
82
+ "flat": "6.0.1",
83
+ "flattie": "1.1.1",
84
+ "miniflare": "^4.20260730.0",
85
+ "nestie": "1.0.3",
86
+ "playwright": "^1.63.0",
87
+ "publint": "^0.3.24",
88
+ "radashi": "12.9.6",
89
+ "tsdown": "^0.23.0",
90
+ "typescript": "^7.0.2",
91
+ "typescript-5.0": "npm:typescript@5.0.4",
92
+ "vitest": "^5.0.1"
93
+ },
94
+ "keywords": [
95
+ "flattify",
96
+ "flatten",
97
+ "unflatten",
98
+ "flat",
99
+ "unflat",
100
+ "nest",
101
+ "unnest",
102
+ "nested",
103
+ "object",
104
+ "keys",
105
+ "paths",
106
+ "dot notation",
107
+ "dot-notation",
108
+ "bracket notation",
109
+ "json pointer",
110
+ "rfc6901",
111
+ "deep",
112
+ "typescript",
113
+ "type inference",
114
+ "prototype pollution",
115
+ "zero dependencies"
116
+ ]
28
117
  }
@@ -0,0 +1,6 @@
1
+ {
2
+ "private": true,
3
+ "main": "../dist/path.cjs",
4
+ "module": "../dist/path.js",
5
+ "types": "../dist/path.d.cts"
6
+ }
package/.editorconfig DELETED
@@ -1,17 +0,0 @@
1
- # EditorConfig helps developers define and maintain consistent
2
- # coding styles between different editors and IDEs
3
- # editorconfig.org
4
-
5
- root = true
6
-
7
- [*]
8
-
9
- indent_style = space
10
- indent_size = 2
11
- end_of_line = lf
12
- charset = utf-8
13
- trim_trailing_whitespace = true
14
- insert_final_newline = true
15
-
16
- [*.md]
17
- trim_trailing_whitespace = false
package/.npmignore DELETED
@@ -1,3 +0,0 @@
1
- node_modules
2
-
3
- .DS_Store
package/CHANGELOG.md DELETED
@@ -1,6 +0,0 @@
1
- # Changelog
2
-
3
- ## Version 1.0.0
4
-
5
- * Initial commit
6
- * Added support to convert objects and arrays to "flat" JSON (plain JSON)
package/index.js DELETED
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * The entry point.
5
- * @module Flattify
6
- */
7
- module.exports = require('./lib/flattify');
package/lib/flattify.js DELETED
@@ -1,60 +0,0 @@
1
- 'use strict';
2
-
3
- var config = {
4
- isFlattifyArray: false
5
- };
6
-
7
- var parseJSON = function (string) {
8
- try {
9
- return JSON.parse(string);
10
- } catch (e) {
11
- return string;
12
- }
13
- };
14
-
15
- var execute = function (json, parent, flattenJson) {
16
- var flattenJson = flattenJson || {};
17
-
18
- for (var property in json) {
19
- if (property !== null) {
20
- switch (Object.prototype.toString.call(json[property])) {
21
- case '[object Array]':
22
- if (config.isFlattifyArray) {
23
- execute(json[property], parent ? parent + '.' + property : property, flattenJson);
24
- } else {
25
- flattenJson[property] = JSON.stringify(json[property]);
26
- }
27
- break;
28
- case '[object Object]':
29
- execute(json[property], parent ? parent + '.' + property : property, flattenJson);
30
- break;
31
- default:
32
- flattenJson[parent? parent + '.' + property : property] = json[property];
33
- }
34
- }
35
- }
36
-
37
- return flattenJson;
38
- };
39
-
40
- var isArray = function (json) {
41
- return Object.prototype.toString.call(json) === '[object Array]';
42
- };
43
-
44
- var flattify = function (json, isFlattifyArray) {
45
- config.isFlattifyArray = !!isFlattifyArray;
46
- json = parseJSON(json);
47
-
48
- if (!isArray(json))
49
- return execute(json);
50
-
51
- var array = [];
52
-
53
- json.forEach(function (item) {
54
- array.push(execute(item));
55
- });
56
-
57
- return array;
58
- };
59
-
60
- module.exports = flattify;