Skip to content

Commit

Permalink
feat: support dot notation like coordinates.1 for headers to parse …
Browse files Browse the repository at this point in the history
…into a nested array
  • Loading branch information
josdejong committed Sep 7, 2023
1 parent 7fd737d commit 67c2685
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
4 changes: 4 additions & 0 deletions src/csv2json.test.ts
Expand Up @@ -228,6 +228,10 @@ describe('csv2json', () => {
])
})

test('should parser nested fields with dot notation for indexes', () => {
expect(csv2json('"nested.geo.0"\r\n42\r\n')).toEqual([{ nested: { geo: [42] } }])
})

test('should parser nested fields containing the key separator and a control character', () => {
expect(csv2json('"nested[""field.,name""]"\r\n42\r\n')).toEqual([
{ nested: { 'field.,name': 42 } }
Expand Down
4 changes: 4 additions & 0 deletions src/path.test.ts
Expand Up @@ -21,7 +21,11 @@ describe('path', () => {
expect(parsePath('name')).toEqual(['name'])
expect(parsePath('address.location[0]')).toEqual(['address', 'location', 0])
expect(parsePath('[0].name')).toEqual([0, 'name'])
expect(parsePath('0.name')).toEqual([0, 'name'])
expect(parsePath('address.location.1')).toEqual(['address', 'location', 1])
expect(parsePath('users.2.name')).toEqual(['users', 2, 'name'])
expect(parsePath('[90].name')).toEqual([90, 'name'])
expect(parsePath('["90"].name')).toEqual(['90', 'name'])
expect(parsePath('["prop.with.dot"]')).toEqual(['prop.with.dot'])
expect(parsePath('["prop with space"]')).toEqual(['prop with space'])
expect(parsePath('["prop with \'\\"]["]')).toEqual(['prop with \'"]['])
Expand Down
8 changes: 5 additions & 3 deletions src/path.ts
Expand Up @@ -46,9 +46,8 @@ export function parsePath(pathStr: string): Path {
eatCharacter('"')
} else {
const prop = parseProp((c) => c === ']')
const index = Number(prop)

path.push(isNaN(index) ? prop : index)
path.push(prop)
}
eatCharacter(']')
} else {
Expand All @@ -70,7 +69,10 @@ export function parsePath(pathStr: string): Path {
}
}

return prop
// match a string with only digits and optional spacing at the start and the end
const digitsRegex = /^ *\d+ *$/

return !unescape && digitsRegex.test(prop) ? parseInt(prop) : prop
}

function eatCharacter(char: string) {
Expand Down

0 comments on commit 67c2685

Please sign in to comment.