Skip to main content

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-Json stops 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 10 or higher when you write JSON back out.
  • Keys that differ only in case, such as Id and id, are legal JSON, but ConvertFrom-Json refuses them. -AsHashtable reads 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).KeysIdidtotalprice

A 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 = pending

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 more

Rules 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 ^json reaches Gronify as json.
  • 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.' matches status = "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

JobToolWhy
Find where a key or value lives in an unfamiliar filegronify searchEach match prints with its full path
Read or filter a field whose path you knowConvertFrom-Json with Where-ObjectBuilt in, and returns objects you can script with
Check whether a string occurs anywhereSelect-String or findstrNo JSON parsing is needed
Search a file too large to loadgronify search with the file pathIt reads the file as a stream
Reshape JSON or compute over itjq, or ConvertFrom-JsonGronify only flattens, filters, and rebuilds
Searching JSON on Windows: built-ins and Gronify

Frequently asked questions

Is there a grep for JSON on Windows?

Select-String and findstr are the built-in line searches, and neither knows JSON structure. npm install -g gronify adds gronify search, which prints each match with its JSON path. Gronify's CI runs the test suite on Windows, Linux, and macOS; the transcripts on this page come from PowerShell 7.4 on Linux.

PowerShell says gronify.ps1 cannot be loaded because running scripts is disabled

npm installs a small .ps1 launcher next to gronify.cmd, and PowerShell's execution policy can block it. Run gronify.cmd instead, or allow local scripts for your account with Set-ExecutionPolicy -Scope CurrentUser RemoteSigned. See about Execution Policies before you change the policy.

Does gronify work in cmd.exe?

The commands are the same. Quote the search term with double quotes, since cmd does not treat single quotes as quotes and reads ^, |, <, and > outside quotes as its own syntax.

Why does ConvertTo-Json print @{...} instead of nested objects?

Its default -Depth is 2, and anything deeper is converted to a string. Pass -Depth with a number at least as deep as your document, for example ConvertTo-Json -Depth 20.

Try it on your own JSON.

Gronify is open source and MIT licensed. Install it with npm or Homebrew, or read the source first.

Install GronifyView the repository