Skip to content
Advertisement

Extract values from complicated JSON based on a specific condition using Java or Python [closed]

I am totally new to JSON. I have a JSON file that contains the following format:

{"A":
     {"B":[
         {"C":{"text":"Command X","meaning":"Read ","http":"some link","Reference":"Reference name"}},
         {"C":{"text":"Command Y","meaning":"Write","http":"some link"}},
         {"C":{"text":"Command Z","meaning":"Read","http":"some link"}}
                      ],
         "context":{"context-id":"6429","section-id":"123","sentence-id":"456","title":"Something","chapter-id":"6","section-title":"Something","sentence-num-in-chapter":"30","section-id":"77","sentence-num-in-section":"1","num-of-sentences":"12","para-id":"0000","subsection-title":"something"},
         "link-id":"123","Command":"XYZ","Sectionlink":"link","command-number":"20.5.1","content-ref":"Something"}
     }
{"A":
....
}

I need to extract the following:

Command":XYZ  command-number :20.5.1    Command X  meaning": Read   Command Z  meaning": Read

Which means: For each A, extract the commands if the meaning of the command is "Read" then extract the general command "XYZ" and the command-number.

Advertisement

Answer

You can import json library and use json.loads() function through python :

import json
s = '{"A":{"B":[{"C":{"text":"Command X","meaning":"Read","http":"some link","Reference":"Reference name"}},{"C":{"text":"Command Y","meaning":"Write","http":"some link"}},{"C":{"text":"Command Z","meaning":"Read","http":"some link"}}],"context":{"context-id":"6429","section-id":"123","sentence-id":"456","title":"Something","chapter-id":"6","section-title":"Something","sentence-num-in-chapter":"30","section-id":"77","sentence-num-in-section":"1","num-of-sentences":"12","para-id":"0000","subsection-title":"something"},"link-id":"123","Command":"XYZ","Sectionlink":"link","command-number":"20.5.1","content-ref":"Something"}}'

ds = json.loads(s)

for dict in ds:
      if dict == 'A':
            A = ds[dict]
            for dict in A:
                  for B in A[dict]:
                        try:
                              if B['C']['meaning']=='Read':
                                    print("text : ",B['C']['text'])
                                    print("Command : ",A['Command'])
                                    print("command-number : ",A['command-number'])
                        except:
                              exit

P.S. : Be careful about the removing of whitespace character after Read value of meaning key.

Advertisement