Convert Json to newline Json standard using Python

前端 未结 2 1438
慢半拍i
慢半拍i 2021-01-27 13:27

I have a code which get nested object and remove all nesting (make the object flat):

def flatten_json(y):
    \"\"\"
    @param y: Unflated Json
    @return: Fla         


        
相关标签:
2条回答
  • 2021-01-27 13:57

    I think you're looking for something like this?

    import json
    
    def create_jsonlines(original):
    
        if isinstance(original, str):
            original = json.loads(original)
    
        return '\n'.join([json.dumps(original[outer_key], sort_keys=True) 
                          for outer_key in sorted(original.keys(),
                                                  key=lambda x: int(x))])
    
    # Added fake record to prove order is sorted
    inp = {
       "3": {"code": "en-FR", "id": 76, "name": "French", "languageName": "French"},
       "0": {"code": "en-GB", "id": 77, "languageName": "English", "name": "English"}, 
       "1": {"code": "de-DE", "id": 78, "languageName": "Deutsch", "name": "German"}
       }
    output = create_jsonlines(inp)
    
    print(output)
    
    0 讨论(0)
  • 2021-01-27 14:03

    Take a look at jsonlines on GitHub and install it from PyPi with pip install jsonlines. The documentation is available here:

    jsonlines is a Python library to simplify working with jsonlines and ndjson data.

    This data format is straight-forward: it is simply one valid JSON value per line, encoded using UTF-8. While code to consume and create such data is not that complex, it quickly becomes non-trivial enough to warrant a dedicated library when adding data validation, error handling, support for both binary and text streams, and so on. This small library implements all that (and more!) so that applications using this format do not have to reinvent the wheel.

    0 讨论(0)
提交回复
热议问题