Search for string in json files

From LemonWiki共筆
Jump to navigation Jump to search

Search for string in multiple JSON files

Approaches[edit]

Approach 1: Content of JSON file contains the keyword(s)[edit]

  • Input: (1) Specify the folder path (2) Specify the keyword(s)
  • Output: file name list
  • Command: find *.json | xargs grep -E "詐騙|詐欺" -sl to find json files which its content contains the string 詐騙 or 詐欺.


Approach 2: The specified index/column contains the keyword(s)[edit]

  • Requirement: Install jq
  • Input: (1) Specify the folder path (2) Specify the keyword(s) (3) Specify the index/column of JSON
  • Output: file name and the value of specified index/column
  • Command 1: find . -name '*.json' | xargs -I {} jq '{"file": input_filename, "MYCOLUMN": ..|.MYCOLUMN?}' {} | jq -c 'select(.MYCOLUMN | contains("詐騙"))' to find json files which content of column MYCOLUMN contains the string 詐騙[1].
  • Command 2 for multiple keywords using boolean OR operator: find . -name '*.json' | xargs -I {} jq '{"file": input_filename, "MYCOLUMN": ..|.MYCOLUMN?}' {} | jq -c 'select(.MYCOLUMN | contains("詐騙") or contains("詐欺"))' to find json files which content of column MYCOLUMN contains the string 詐騙 or 詐欺.
  • Command 3 for multiple keywords using boolean AND operator: find . -name '*.json' | xargs -I {} jq '{"file": input_filename, "MYCOLUMN": ..|.MYCOLUMN?}' {} | jq -c 'select(.MYCOLUMN | contains("詐騙") and contains("詐欺"))' to find json files which content of column MYCOLUMN contains the string 詐騙 and 詐欺.

References[edit]