Extract all keys from an object (json)
JavaScript (V8), 72 bytes
An edited version to support literal false
, true
and null
values.
f=(o,s)=>!o|[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))
Try it online!
JavaScript (V8), 69 bytes
Takes a native JSON object as input. Prints the results, using a comma as the delimiter.
f=(o,s)=>[o]==o||Object.keys(o).map(k=>f(o[k],k=s?s+[,k]:k,print(k)))
Try it online!
How?
This is a recursive function walking through the keys at the root level and then in each sub-tree of the structure.
We need to process recursive calls on objects and arrays and to stop on strings and numbers. This is achieved with [o]==o||Object.keys(o)
:
type of o | [o]==o | Object.keys(o) | string coercion example
-----------+-----------+-----------------+-------------------------------------
array | false | 0-based indices | ['foo', 'bar'] -> 'foo,bar'
object | false | native keys | {abc: 'xyz'} -> '[object Object]'
string | true | n/a | 'hello' -> 'hello'
number | true | n/a | 123 -> '123'
Ruby, 108 146 115 92 bytes
+38 bytes to fix test cases for objects inside arrays.....
-31 bytes because we can take a parsed JSON object as input now.
-17 bytes by removing the duplicated flat_map
usage.
f=->j,x=''{z=j==[*j]?[*0...j.size]:j.keys rescue[];z.flat_map{|k|[r=x+k.to_s]+f[j[k],r+?.]}}
Try it online!
JavaScript (Node.js), 75 bytes
f=o=>Object.keys(o+''===o||o||0).flatMap(k=>[k,...f(o[k]).map(i=>k+'.'+i)])
Try it online!