12

I have this JSON file called test.json which says:

{
    "test":true,
    "limit": 
    {
        "min":0.5,
        "max":1.5
    }
}

I'd like to be able to read this file in the Windows command line and have these objects parsed as variables.

How would I do this?

1
  • @Manish - Could you give me an example? Commented Oct 14, 2013 at 8:34

3 Answers 3

11

If you use Windows Powershell as your command line, you can use the ConvertFrom-JSON cmdlet: http://powershelljson.codeplex.com/

Make sure your PowerShell version is above 3.0, as ConvertFrom-JSON is available from that version.

If you use plain old CMD, you'll need an external tool for it. I like jq: http://stedolan.github.io/jq/. The tutorial uses curl for the examples, but you can just as easily use echo or read the JSON from a file.

Sign up to request clarification or add additional context in comments.

8 Comments

I'm afraid I can't use Powershell.
See the second part of my answer
We have the exact same reputations core btw :P
To answer my own question: FOR /F "delims=" %%i in ('type test.json ^| jq .limit.min') DO SET min=%%i
Note that you don't need to use type here - you can use the file redirection operator <, and write 'jq .limit.min ^< test.json'.
|
1

PowerShell example. Create from file: $js = Get-Content file.json | ConvertFrom-Json. Get subkey: $js.key.subkey

1 Comment

This should be the very best answer. Works for me, without installing anything.
0

I'd like to be able to read this file in the Windows command line and have these objects parsed as variables.

The JSON-parser can help in this regard:

xidel -s "test.json" -e "$json/limit/min" -e "$json/limit/max"
xidel -s "test.json" -e "$json/limit/(min,max)"

Whether you use 2 queries to return each value, or 1 query to return both values, both commands should return:

0.5
1.5

Let Xidel export these values with custom variable-names or with the key-names as variable-names:

FOR /F "delims=" %A IN ('
  xidel -s "test.json" -e "min:=$json/limit/min" -e "max:=$json/limit/max" --output-format^=cmd
') DO %A
FOR /F "delims=" %A IN ('
  xidel -s "test.json" -e "$json/limit/(min:=min,max:=max)" --output-format^=cmd
') DO %A

FOR /F "delims=" %A IN ('
  xidel -s "test.json" -e "$json/(limit)() ! eval(`{.}:=$json/limit/{.}`)[0]" --output-format^=cmd
') DO %A

ECHO %min% %max%
0.5 1.5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.