![쉘을 사용하여 JSON 파일을 편집하는 방법은 무엇입니까?](https://linux55.com/image/191100/%EC%89%98%EC%9D%84%20%EC%82%AC%EC%9A%A9%ED%95%98%EC%97%AC%20JSON%20%ED%8C%8C%EC%9D%BC%EC%9D%84%20%ED%8E%B8%EC%A7%91%ED%95%98%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F.png)
JSON 파일을 사용하는 쉘 스크립트를 작성 중입니다.
{
"property1": true,
"list": [
{
"id": 1,
"name": "APP1"
},
{
"id": 2,
"name": "APP2"
}
],
"property2": false
}
name
list
이를 읽고 목록에서 상위 개체를 제거하려면 쉘 스크립트를 사용해야 합니다 . 기본적으로 APP1
shell 을 사용하여 이름이 있는 개체를 삭제 해야 합니다 list
. JSON 구조 편집은 옵션이 아닙니다.
답변1
답변2
저는 JSON 읽기/쓰기 기능이 내장된 Python으로 스크립트를 작성할 것입니다.
myfile.json
OP의 JSON 개체가 포함된 파일이 제공됩니다 .
#!/usr/bin/env python # Use the Python interpreter
from json import load, dump # Import the JSON file read and write functions
with open("myfile.json", "r") as file_object: # Open the JSON file for reading
json_data = load(file_object) # Load the data into a dictionary
new_list = [item for item in json_data["list"] if item["name"] != "APP1"] # Make a new list without the item that should be removed
json_data["list"] = new_list # Update the dictionary with the new list
with open("myfile.json", "w") as file_object: # Open the JSON file for writing and truncate it
dump(json_data, file_object) # Write the file back to disk
답변3
답변4
제임스 콜이 보여준 것처럼 그리고 아론 F., 대신 Python을 사용 jq
합니다 zq
. 이 작업은 .list
원래 배열과 동일하지 않은 .name
요소 로 배열을 설정합니다 APP1
.
$ jq '.list |= map(select(.name != "APP1"))' file
{
"property1": true,
"list": [
{
"id": 2,
"name": "APP2"
}
],
"property2": false
}