diff --git a/README.md b/README.md index cd4c2fb..50206e8 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,8 @@ dic = { ``` which you want to flatten. Just apply ```flatten_json```: ```python -from flatten_json import flatten_json -flatten_json(dic) +from flatten_json import flatten +flatten(dic) ``` Results: @@ -34,16 +34,16 @@ Results: ### Usage with Pandas For the following object: -```javascript +```python dic = [ {"a": 1, "b": 2, "c": {"d": 3, "e": 4}}, {"a": 0.5, "c": {"d": 3.2}}, {"a": 0.8, "b": 1.8}, ] ``` -We can apply ```flatten_json``` to each element in the array and then use pandas to capture the output as a dataframe. +We can apply `flatten` to each element in the array and then use pandas to capture the output as a dataframe: ```python -dic_flattened = [flatten_json(d) for d in dic] +dic_flattened = [flatten(d) for d in dic] ``` which creates an array of flattened objects: ```python @@ -64,4 +64,14 @@ The final result as a Pandas dataframe: 2 0.8 1.8 NaN NaN ``` -### \ No newline at end of file +### Custom separator +By default `_` is used to separate nested element. You can change this by passing the desired character: +```python +flatten({"a": [1]}, '|') +``` +returns: +```python +{'a|0': 1} +``` + +Thanks to @jvalhondo, @drajen, and @azaitsev for pointing this out. \ No newline at end of file diff --git a/flatten_json.py b/flatten_json.py index 705686b..c8c02f9 100644 --- a/flatten_json.py +++ b/flatten_json.py @@ -5,13 +5,15 @@ def _join_all(*x): def flatten_json(input_, separator="_"): output = {} - def flatten(object_, name): + def _flatten(object_, name): if isinstance(object_, dict): - [flatten(object_[key], _join_all(name, separator, key)) for key in object_] + [_flatten(object_[key], _join_all(name, separator, key)) for key in object_] elif isinstance(object_, list): - [flatten(item, _join_all(name, separator, index)) for index, item in enumerate(object_)] + [_flatten(item, _join_all(name, separator, index)) for index, item in enumerate(object_)] else: output[name] = object_ - flatten(input_, None) + _flatten(input_, None) return output + +flatten = flatten_json