简体   繁体   中英

Write JSON to a file in pretty print format in Django

I need to create some JSON files for exporting data from a Django system to Google Big Query.

The problem is that Google BQ imposes some characteristics in the JSON file, for example, that each object must be in a different line.

json.dumps writes a stringified version of the JSON, so it is not useful for me.

Django serializes writes better JSON, but it put all in one line. All the information I found about pretty-printing is about json.dumps, which I cannot use.

I will like to know if anyone knows a way to create a JSON file in the format required by Big Query.

Example:

    JSONSerializer = serializers.get_serializer("json")
    json_serializer = JSONSerializer()
    data_objects = DataObject.objects.all()
    with open("dataobjects.json", "w") as out:
        json_serializer.serialize(data_objects, stream=out)

json.dumps is OK. You have to use indent like this.

import json
myjson = '{"latitude":48.858093,"longitude":2.294694}'
mydata = json.loads(myjson)
print(json.dumps(mydata, indent=4, sort_keys=True))

Output:

{
    "latitude": 48.858093,
    "longitude": 2.294694
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM