Search nested JSON in PowerShell and cmd without grep
Windows has no grep, and the closest built-ins each miss half the job: Select-String matches lines without knowing where they sit in the JSON, and ConvertFrom-Json loads the document so you can navigate it once you know the path. gronify search orders.json pending prints every match with its full path, such as json.orders[2].status = "pending", and runs the same way in PowerShell, cmd, and a Unix shell.
Updated
Select-String has the same problem as grep
Select-String is PowerShell's line search. Like grep, it works one line at a time, and a minified JSON file is one line. The examples use the small orders payload from how to grep JSON, saved as orders.json:
Select-String pending orders.jsonorders.json:1:{"service":{"name":"checkout","status":"degraded"},"orders":[{"id":1001,"status":"shipped","customer":{"email":"ada@example.com"}},{"id":1002,"status":"Pending","customer":{"email":"grace@example.com"}},{"id":1003,"status":"pending","customer":{"email":"alan@example.org"},"error":{"code":"CARD_DECLINED"}}]}On a pretty-printed copy each key gets its own line, and the match loses its parents. Line 23 says some status is pending; it does not say which order:
Select-String pending orders.pretty.jsonorders.pretty.json:16: "status": "Pending",orders.pretty.json:23: "status": "pending",Unlike grep, Select-String ignores case by default, so it found Pending too. -CaseSensitive turns that off, and -Context prints neighbouring lines, which helps only when the parent key happens to be a few lines up. findstr in cmd has the same one-line view and a smaller regex syntax: it has no | alternation.
ConvertFrom-Json answers questions you already know how to ask
ConvertFrom-Json parses the text into PowerShell objects. Once you know the shape, that is the PowerShell equivalent of jq: filter with Where-Object and read a field by its path.
$doc = Get-Content orders.json -Raw | ConvertFrom-Json$doc.orders | Where-Object status -eq 'pending' | Select-Object id, statusid : 1002status : Pendingid : 1003status : pending$doc.orders | Where-Object status -ceq 'pending' | Select-Object id, statusid : 1003status : pending$doc.orders[2].error.codeCARD_DECLINED-eq compares strings without case in PowerShell; -ceq is the exact match. The catch is the first step: to write $doc.orders[2].error.code you must already know that error.code lives under orders. For a file you have not seen, PowerShell has no built-in that lists every path. Three more things trip people up:
ConvertTo-Jsonstops at depth 2 by default. PowerShell 7.4 prints a warning and turns deeper objects into strings such as"@{email=ada@example.com}". Pass-Depth 10or higher when you write JSON back out.- Keys that differ only in case, such as
Idandid, are legal JSON, butConvertFrom-Jsonrefuses them.-AsHashtablereads them, and Microsoft's documentation lists it as added in PowerShell 6.0, so Windows PowerShell 5.1 does not have it. - The whole file is read into one string and then into objects, so memory grows with the file.
$doc | ConvertTo-JsonWARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.{ "service": { "name": "checkout", "status": "degraded" }, "orders": [ { "id": 1001, "status": "shipped", "customer": "@{email=ada@example.com}" }, { "id": 1002, "status": "Pending", "customer": "@{email=grace@example.com}" }, { "id": 1003, "status": "pending", "customer": "@{email=alan@example.org}", "error": "@{code=CARD_DECLINED}" } ]}Get-Content keys.json{"Id":"A-17","id":17,"total":12345678901234567890,"price":1.10}Get-Content keys.json -Raw | ConvertFrom-JsonConvertFrom-Json: Cannot convert the JSON string because it contains keys with different casing. Please use the -AsHashTable switch instead. The key that was attempted to be added to the existing key 'Id' was 'id'.(Get-Content keys.json -Raw | ConvertFrom-Json -AsHashtable).KeysIdidtotalpriceA path walker in plain PowerShell
If you cannot install anything, a short recursive function prints each value with its path, and Select-String can filter that. It needs PowerShell 6 or newer for -AsHashtable, loads the whole file, and prints strings without their quotes:
function Get-JsonPath($Node, $Path = 'json') {>> if ($Node -is [System.Collections.IDictionary]) {>> foreach ($key in $Node.Keys) { Get-JsonPath $Node[$key] "$Path.$key" }>> } elseif ($Node -is [System.Collections.IList]) {>> for ($i = 0; $i -lt $Node.Count; $i++) { Get-JsonPath $Node[$i] "$Path[$i]" }>> } else {>> "$Path = $Node">> }>> }Get-JsonPath (Get-Content orders.json -Raw | ConvertFrom-Json -AsHashtable) | Select-String pendingjson.orders[1].status = Pendingjson.orders[2].status = pendingSearch JSON by path with gronify search
Gronify does the walk and the filter in one streaming pass and keeps JSON types in the output, so strings stay quoted. It is an npm package: on Windows, install Node.js 20 or newer, then run npm install -g gronify. It needs neither grep, WSL, nor Git Bash.
gronify search orders.json pendingjson.orders[1].status = "Pending"json.orders[2].status = "pending"gronify search orders.json -c pendingjson.orders[2].status = "pending"gronify search orders.json --regex 'orders\[[0-9]+\]\.customer\.email'json.orders[0].customer.email = "ada@example.com"json.orders[1].customer.email = "grace@example.com"json.orders[2].customer.email = "alan@example.org"Like Select-String, a search ignores case unless you ask otherwise. In Gronify that switch is -c (long form --case-sensitive). --regex takes a JavaScript regular expression, which is close to the .NET syntax Select-String uses for anchors, classes, groups, and |.
gronify search orders.json --count status4gronify search orders.json -m 2 statusjson.service.status = "degraded"json.orders[0].status = "shipped"Stopped after 2 matches (--max-count); there may be moregronify search --exit-status orders.json refunded; $LASTEXITCODEWarning: No matches found for 'refunded'Tip: Search is a case-insensitive substring match; use --regex for patterns1--count prints the number of matching lines. -m 2 stops reading the file after two matches. With --exit-status, $LASTEXITCODE is 0 when something matched, 1 when nothing did, and 2 on an error, so if ($LASTEXITCODE -eq 1) works in a script. The warning and the Stopped after notice go to stderr, so they stay out of a redirected file. The flags are explained in full in how to grep JSON.
Quoting search terms in PowerShell and cmd
Most failed searches on Windows are quoting problems, not JSON problems. PowerShell expands $name inside double quotes, and OpenAPI files are full of $ref keys. Here PowerShell replaced "$ref" with the value of the unset variable $ref, an empty string. Gronify received an empty term, so it treated the run as a search of standard input, and nothing was piped in:
gronify search orders.json "$ref" --countError: No input file provided and no data piped to stdinUsage: gronify search <file> <term> OR cat file.json | gronify search <term>Single quotes pass the text through unchanged, $ and double quotes included. This finds where the GitHub REST API description refers to its simple-user schema:
gronify search api.github.com.json -m 2 '$ref = "#/components/schemas/simple-user"'json.paths["/orgs/{org}/blocks"].get.responses["200"].content["application/json"].schema.items.$ref = "#/components/schemas/simple-user"json.paths["/orgs/{org}/members"].get.responses["200"].content["application/json"].schema.items.$ref = "#/components/schemas/simple-user"Stopped after 2 matches (--max-count); there may be moreRules that hold in both shells:
- In PowerShell, put every regex in single quotes. To include a single quote, double it:
'it''s'. - cmd does not treat single quotes as quotes, so use double quotes there. Outside quotes cmd reads
^as its escape character and|,<, and>as operators, so an unquoted^jsonreaches Gronify asjson. - Double quotes inside a double-quoted argument are escaped differently by each shell. You can often avoid them:
.matches the quote character in a regex, so--regex 'status = .pending.'matchesstatus = "pending"in any shell.
gronify search orders.json --regex 'status = .pending.' -cjson.orders[2].status = "pending"Pipelines, Get-Content, and output files
Gronify reads standard input when you leave out the file name, so a PowerShell pipeline can feed it. The output is plain text lines, so Select-String can filter gronify flatten the way grep does on Linux:
Get-Content orders.json -Raw | gronify search -m 1 emailjson.orders[0].customer.email = "ada@example.com"Stopped after 1 match (--max-count); there may be moregronify flatten orders.json | Select-String customerjson.orders[0].customer = {}json.orders[0].customer.email = "ada@example.com"json.orders[1].customer = {}json.orders[1].customer.email = "grace@example.com"json.orders[2].customer = {}json.orders[2].customer.email = "alan@example.org"For a large file, pass the path instead of piping Get-Content: Gronify then streams the file itself, while Get-Content -Raw builds the whole file as one string first. To save results, use -o rather than >. It writes the file only after the run succeeds, and the bytes are exactly what Gronify produced, whatever encoding the shell's > would pick:
gronify search orders.json CARD_DECLINED -o declined.txt; Get-Content declined.txtOutput written to declined.txtjson.orders[2].error.code = "CARD_DECLINED"To get JSON back, pipe lines into gronify unflatten. unflatten fills in missing parent containers automatically, so both filtered searches and inverted -v searches rebuild valid JSON. Here -v drops orders and keeps the rest:
gronify search orders.json -v orders | gronify unflatten{"service":{"name":"checkout","status":"degraded"}}Which tool to use on Windows
| Job | Tool | Why |
|---|---|---|
| Find where a key or value lives in an unfamiliar file | gronify search | Each match prints with its full path |
| Read or filter a field whose path you know | ConvertFrom-Json with Where-Object | Built in, and returns objects you can script with |
| Check whether a string occurs anywhere | Select-String or findstr | No JSON parsing is needed |
| Search a file too large to load | gronify search with the file path | It reads the file as a stream |
| Reshape JSON or compute over it | jq, or ConvertFrom-Json | Gronify only flattens, filters, and rebuilds |