I checked the method when converting (compressing) JSON character string to 1 line JSON, so make a note.
The following two methods will be introduced.
Assuming the following JSON character string described in the file.
file.py
{
"Records": [
{
"database": {
"NewImage": {
"eventId": {
"S": "a4207f7a-5f04-471b-a338-1175182eaa6d"
},
"isCompleted": {
"BOOL": True
}
},
"OldImage": {
"eventId": {
"S": "a4207f7a-5f04-471b-a338-1175182eaa6d"
},
"isCompleted": {
"BOOL": False
}
}
}
}
]
}
$ python
>>> import json
>>> f = open("file.json")
>>> json.dumps(f.read()).replace("\\n","").replace("\\","").replace(" ", "")
'"{"Records": [{"database": {"NewImage": {"eventId": {"S": "a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted": {"BOOL": True}},"OldImage": {"eventId": {"S": "a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted": {"BOOL": False}}}}]}"'
In .replace ("", "")
, the indent (space`` 4) is replaced and deleted. If a different character string is indented in the JSON character string, the replacement source of this part should be changed.
Basically, cat <filename> | jq -c
can be used.
However, jq cannot handle True
and False
as boolean, so if you try to execute it as it is for this file.json, the following error will occur.
$ cat file.json | jq -c
parse error: Invalid numeric literal at line 11, column 0
Therefore, it is necessary to change True
to true
and False
to false
in advance. If file.json is modified in advance, it can be executed as follows.
$ cat file.json | jq -c
{"Records":[{"database":{"NewImage":{"eventId":{"S":"a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted":{"BOOL":true}},"OldImage":{"eventId":{"S":"a4207f7a-5f04-471b-a338-1175182eaa6d"},"isCompleted":{"BOOL":false}}}}]}
that's all
Recommended Posts