JSON의 패턴을 기반으로 찾기 및 바꾸기

crajuc 휴스턴

URL을 기반으로 내가 uri좋아 하는 것을 찾고 에서 Test123.elb.us-east-1.amazonaws.com변경해야 합니다.connectionIdhkl876xed763

예 : 에서 Test999.elb.us-east-1.amazonaws.com업데이트connectionIdhkl876klm812

다음은 파일의 샘플 콘텐츠입니다.

   "x-amazon-apigateway-integration": {
      "uri": "http://Test123.elb.us-east-1.amazonaws.com:8765/emote",
      "responses": {
        "200": {
          "statusCode": "200",
          ......
          ......

      "connectionType": "VPC_LINK",
      "connectionId": "hkl876",
      "httpMethod": "POST",
      "type": "http"
    }
  },
    "x-amazon-apigateway-integration": {
      "uri": "http://Test999.elb.us-east-1.amazonaws.com:4567/authcode/v1/remote",
      "responses": {
        "200": {
          "statusCode": "200",
          ......
          ......

      "connectionType": "VPC_LINK",
      "connectionId": "hkl876",
      "httpMethod": "PUT",
      "type": "http"
    }

제안 해 주셔서 감사합니다.

전체 json 파일 에서이 솔루션을 시도하면 오류 메시지가 나타납니다.

Traceback (most recent call last):
  File "sample.py", line 16, in <module>
    if data[key]['uri'].find("test123.elb.us-east-1.amazonaws.com") > 0:
TypeError: string indices must be integers

다음은 한 레코드에 대한 전체 swagger 파일입니다.

{
  "swagger": "2.0",
  "info": {
    "version": "2019-02-19T19:13:11Z"
  },
  "host": "abc.com",
  "schemes": [
    "http"
  ],
  "paths": {
    "/code123": {
      "post": {
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "x-correlationid",
            "in": "header",
            "required": true,
            "type": "string"
          },
          {
            "name": "content-type",
            "in": "header",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            },
            "headers": {
              "Access-Control-Allow-Origin": {
                "type": "string"
              }
            }
          },
          "security": [
            {
              "RequestTokenAuthorizer": []
            },
            {
              "api_key": []
            }
          ],
          "x-amazon-apigateway-integration": {
            "uri": "http://test123.elb.us-east-1.amazonaws.com:2768/sample/code",
            "responses": {
              "200": {
                "statusCode": "200",
                "responseParameters": {
                  "method.response.header.Access-Control-Allow-Origin": "'*'"
                }
              },
              "requestParameters": {
                "integration.request.header.x-correlationid": "method.request.header.x-correlationid",
                "integration.request.header.x-brand": "method.request.header.x-brand"
              },
              "passthroughBehavior": "when_no_templates",
              "connectionType": "VPC_LINK",
              "connectionId": "xyz879",
              "httpMethod": "POST",
              "type": "http"
            }
          }
        }
      }
    }
  }
}
앤디 달튼

와 같은 것을 사용하여이 작업을 수행하는 더 좋은 방법이있을 수 jq있지만 해당 도구를 마스터 한 적이 없습니다. 저에게는 Python을 사용합니다. 업데이트 된 JSON 문서가 주어지면 :

{
  "swagger": "2.0",
  "info": {
    "version": "2019-02-19T19:13:11Z"
  },
  "host": "abc.com",
  "schemes": [
    "http"
  ],
  "paths": {
    "/code123": {
      "post": {
        "produces": [
          "application/json"
        ],
        "parameters": [
          {
            "name": "x-correlationid",
            "in": "header",
            "required": true,
            "type": "string"
          },
          {
            "name": "content-type",
            "in": "header",
            "required": true,
            "type": "string"
          }
        ],
        "responses": {
          "200": {
            "description": "200 response",
            "schema": {
              "$ref": "#/definitions/Empty"
            },
            "headers": {
              "Access-Control-Allow-Origin": {
                "type": "string"
              }
            }
          },
          "security": [
            {
              "RequestTokenAuthorizer": []
            },
            {
              "api_key": []
            }
          ],
          "x-amazon-apigateway-integration": {
            "uri": "http://test123.elb.us-east-1.amazonaws.com:2768/sample/code",
            "responses": {
              "200": {
                "statusCode": "200",
                "responseParameters": {
                  "method.response.header.Access-Control-Allow-Origin": "'*'"
                }
              },
              "requestParameters": {
                "integration.request.header.x-correlationid": "method.request.header.x-correlationid",
                "integration.request.header.x-brand": "method.request.header.x-brand"
              },
              "passthroughBehavior": "when_no_templates",
              "connectionType": "VPC_LINK",
              "connectionId": "xyz879",
              "httpMethod": "POST",
              "type": "http"
            }
          }
        }
      }
    }
  }
}

이 Python 스크립트 실행 (위의 예 이름이 ex.json) :

#!/usr/bin/env python3

import json

with open('ex.json') as json_file:
    data = json.load(json_file)

    for path in data['paths']:
        for method in data['paths'][path]:
                if data['paths'][path][method]['responses']['x-amazon-apigateway-integration']['uri'].find("test123.elb.us-east-1.amazonaws.com") > 0:
                    data['paths'][path][method]['responses']['x-amazon-apigateway-integration']['responses']['connectionId'] = 'xed763'

    print(json.dumps(data, indent=4))

connectionId첫 번째 항목 필드가 변경된 다음 출력을 가져옵니다 .

{
    "swagger": "2.0",
    "info": {
        "version": "2019-02-19T19:13:11Z"
    },
    "host": "abc.com",
    "schemes": [
        "http"
    ],
    "paths": {
        "/code123": {
            "post": {
                "produces": [
                    "application/json"
                ],
                "parameters": [
                    {
                        "name": "x-correlationid",
                        "in": "header",
                        "required": true,
                        "type": "string"
                    },
                    {
                        "name": "content-type",
                        "in": "header",
                        "required": true,
                        "type": "string"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "200 response",
                        "schema": {
                            "$ref": "#/definitions/Empty"
                        },
                        "headers": {
                            "Access-Control-Allow-Origin": {
                                "type": "string"
                            }
                        }
                    },
                    "security": [
                        {
                            "RequestTokenAuthorizer": []
                        },
                        {
                            "api_key": []
                        }
                    ],
                    "x-amazon-apigateway-integration": {
                        "uri": "http://test123.elb.us-east-1.amazonaws.com:2768/sample/code",
                        "responses": {
                            "200": {
                                "statusCode": "200",
                                "responseParameters": {
                                    "method.response.header.Access-Control-Allow-Origin": "'*'"
                                }
                            },
                            "requestParameters": {
                                "integration.request.header.x-correlationid": "method.request.header.x-correlationid",
                                "integration.request.header.x-brand": "method.request.header.x-brand"
                            },
                            "passthroughBehavior": "when_no_templates",
                            "connectionType": "VPC_LINK",
                            "connectionId": "xed763",
                            "httpMethod": "POST",
                            "type": "http"
                        }
                    }
                }
            }
        }
    }
}

Python 스크립트 :

  1. 파일 ex.json을 열고 해당 파일을 엽니 다.json_file
  2. JSON을 다음 이름의 파이썬 사전으로 읽어들입니다. data
  3. 문서의 경로를 통해 루프 (예 /code123)
  4. 각 경로에 대한 방법을 통해 루프 (예 post)
  5. uri해당 요소 필드에 대상 문자열이 포함되어 있는지 확인 합니다. find()문자열이 없으면 -1을 반환합니다.
  6. 는 IF uri주어진에서이 key당신이 찾고있는 문자열을 포함, 그것은 덮어 connectionId당신이 원하는 값으로 필드를
  7. 루프가 완료되면 (잠재적으로 수정 된) JSON을 표준 출력으로 인쇄합니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Javascript의 패턴을 기반으로 단어 바꾸기

분류에서Dev

PowerShell의 패턴을 기반으로 XML 노드 및 값 추출

분류에서Dev

Python의 이메일 주소 및 이름을 기반으로 가장 일반적인 이메일 패턴 찾기

분류에서Dev

jquery : 일치하는 패턴으로 모든 id 속성 찾기 및 바꾸기

분류에서Dev

regexprep을 사용하여 매우 구체적인 패턴 찾기 및 바꾸기

분류에서Dev

찾기 및 바꾸기위한 정규식 패턴

분류에서Dev

동적 정규식 찾기 및 패턴 바꾸기

분류에서Dev

마지막 공백 뒤에서 패턴 찾기 및 바꾸기

분류에서Dev

열 값의 패턴을 열 값으로 바꾸기

분류에서Dev

문자열의 패턴을 값 목록으로 바꾸기 (SQL)

분류에서Dev

Nodejs-JSON을 반복하여 문자열 찾기 및 바꾸기

분류에서Dev

키로 찾기 및 중첩 된 json 객체의 값으로 바꾸기

분류에서Dev

사전을 기반으로 검색 및 바꾸기

분류에서Dev

awk 찾기 및 바꾸기

분류에서Dev

찾기 및 바꾸기 : \ '

분류에서Dev

sed 명령-찾기에서 특정 패턴을 제외하면서 찾기 및 바꾸기

분류에서Dev

파일의 파일 이름을 루프로 일괄 찾기 및 바꾸기

분류에서Dev

파이썬의 패턴을 기반으로 문자열 분할 및 그룹화

분류에서Dev

Sed : 다음 줄로 둘러싸 이는 패턴 찾기 및 바꾸기

분류에서Dev

패턴 'n'+ (자음)을 효율적으로 찾고 바꾸기

분류에서Dev

정규식 일치 및 패턴으로 바꾸기

분류에서Dev

Python의 반복 정규식 : 찾기 및 바꾸기

분류에서Dev

모든 RegEx 패턴을 원래의 스팅을 기반으로 새 문자열로 바꾸는 방법-JavaScript

분류에서Dev

파일의 특정 패턴을 sed로 바꾸거나 바꾸기

분류에서Dev

문자열 목록 및 해당 대체 목록을 기반으로 파일의 문자열 바꾸기

분류에서Dev

찾기 및 이름 바꾸기를 사용하여 반복적으로 모든 파일과 폴더에 사용자 정의 문자열을 추가합니다.

분류에서Dev

다른 배열을 기반으로 배열의 값 바꾸기

분류에서Dev

찾기 및 바꾸기를 사용하지 않는 파일의 값을 바꾸는 sed 명령

분류에서Dev

Excel에서 2 개의 Excel 파일로 찾기 및 바꾸기

Related 관련 기사

  1. 1

    Javascript의 패턴을 기반으로 단어 바꾸기

  2. 2

    PowerShell의 패턴을 기반으로 XML 노드 및 값 추출

  3. 3

    Python의 이메일 주소 및 이름을 기반으로 가장 일반적인 이메일 패턴 찾기

  4. 4

    jquery : 일치하는 패턴으로 모든 id 속성 찾기 및 바꾸기

  5. 5

    regexprep을 사용하여 매우 구체적인 패턴 찾기 및 바꾸기

  6. 6

    찾기 및 바꾸기위한 정규식 패턴

  7. 7

    동적 정규식 찾기 및 패턴 바꾸기

  8. 8

    마지막 공백 뒤에서 패턴 찾기 및 바꾸기

  9. 9

    열 값의 패턴을 열 값으로 바꾸기

  10. 10

    문자열의 패턴을 값 목록으로 바꾸기 (SQL)

  11. 11

    Nodejs-JSON을 반복하여 문자열 찾기 및 바꾸기

  12. 12

    키로 찾기 및 중첩 된 json 객체의 값으로 바꾸기

  13. 13

    사전을 기반으로 검색 및 바꾸기

  14. 14

    awk 찾기 및 바꾸기

  15. 15

    찾기 및 바꾸기 : \ '

  16. 16

    sed 명령-찾기에서 특정 패턴을 제외하면서 찾기 및 바꾸기

  17. 17

    파일의 파일 이름을 루프로 일괄 찾기 및 바꾸기

  18. 18

    파이썬의 패턴을 기반으로 문자열 분할 및 그룹화

  19. 19

    Sed : 다음 줄로 둘러싸 이는 패턴 찾기 및 바꾸기

  20. 20

    패턴 'n'+ (자음)을 효율적으로 찾고 바꾸기

  21. 21

    정규식 일치 및 패턴으로 바꾸기

  22. 22

    Python의 반복 정규식 : 찾기 및 바꾸기

  23. 23

    모든 RegEx 패턴을 원래의 스팅을 기반으로 새 문자열로 바꾸는 방법-JavaScript

  24. 24

    파일의 특정 패턴을 sed로 바꾸거나 바꾸기

  25. 25

    문자열 목록 및 해당 대체 목록을 기반으로 파일의 문자열 바꾸기

  26. 26

    찾기 및 이름 바꾸기를 사용하여 반복적으로 모든 파일과 폴더에 사용자 정의 문자열을 추가합니다.

  27. 27

    다른 배열을 기반으로 배열의 값 바꾸기

  28. 28

    찾기 및 바꾸기를 사용하지 않는 파일의 값을 바꾸는 sed 명령

  29. 29

    Excel에서 2 개의 Excel 파일로 찾기 및 바꾸기

뜨겁다태그

보관