How to find a particular json value by key?

前端 未结 8 1871
再見小時候
再見小時候 2020-11-29 04:23

There is a json like this:

{
  \"P1\": \"ss\",
  \"Id\": 1234,
  \"P2\": {
      \"P1\": \"cccc\"
  },
  \"P3\": [
      {
          \"P1\": \"aaa\"
      }
         


        
8条回答
  •  误落风尘
    2020-11-29 04:38

    Bearing in mind that json is simply a string, using regular expressions with look-ahead and look-behind can accomplish this task very quickly.

    Typically, the json would have been extracted from a request to external api, so code to show how that would work has been included but commented out.

    import re
    #import requests
    #import json
    
    #r1 = requests.get( ... url to some api ...)
    #JSON = str(json.loads(r1.text))
    JSON = """
     {
      "P1": "ss",
      "Id": 1234,
      "P2": {
          "P1": "cccc"
      },
      "P3": [
         {
              "P1": "aaa"
         }
      ]
     }
    """
    rex1  = re.compile('(?<=\"P1\": \")[a-zA-Z_\- ]+(?=\")')
    rex2 = rex1.findall(JSON)  
    print(rex2)
    
    #['ss', 'cccc', 'aaa']
    

提交回复
热议问题