Skip to content

Commit

Permalink
Updated readme, added a flatten reference to flatten_json
Browse files Browse the repository at this point in the history
  • Loading branch information
amirziai committed Feb 1, 2017
1 parent 8016688 commit 3709bb5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
22 changes: 16 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand All @@ -64,4 +64,14 @@ The final result as a Pandas dataframe:
2 0.8 1.8 NaN NaN
```

###
### 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.
10 changes: 6 additions & 4 deletions flatten_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 3709bb5

Please sign in to comment.