skip to Main Content

I have a JSON file, demo.json, like this:

{"status":true,"code":300,"msg":"6e8987cfb05d647c2c0164043b25de7420230522111435","data":[{"ip":"1.2.3.4","sign":"dd9bde86cc8d360c7a346ad2611a19b9"},{"ip":"5.6.7.8","sign":"2f5ad72febe3e0f49354ef0db1edc642"}]
}

How can I get the IP list with a Windows batch script?

2

Answers


  1. Short answer: you can’t. At least not with a Windows default tools. Is it impossible? No.

    1. Windows batch scripts
      The naive method is to parse the text, but I don’t recommend it. It’s slow, inefficient, difficult to scale and not reliable code-wise, not to mention a hell to maintain when you need to update or fix the code.

    A proper way is to use a command line tool, unfortunately, I don’t know of any built-in tool that can parse json. However, we can use external tools and integrate them in the windows batch shell. One such utility is ./jq

    Pros: ./jq is cross-platform, so if you will need to move to some other OS, it won’t have much of an impact.

    Cons: First of all, it’s an external tool, so that means you need to get it from a third party. Secondly, if it’s for work, chances are company security policies won’t let you download exe files or run unknown executables. If it’s for a personal project which you share with others they might be cautious about running an unknown exe that does god-knows-what (from their point of view).

    Example: jq-win64.exe -r "."data" | .[] ."ip"" test.json

    1. Of course, if you want to align with how Microsoft wants users/admins to automate Windows, you have the option of using PowerShell. It has built-in support for XML and JSON.

    Pros: It’s fast, efficient and built-in, not to mention it has support for tons of things.

    Cons: If it’s for work, security policies won’t let you download exe files or run PS scripts.

    Example: (Get-Content .test.json -Raw | ConvertFrom-Json).data.ip

    1. VBScript

    Similar to #1. You can use vbsEdit or maybe some repositories on GitHub (such as this one). Note: I haven’t tried either. And similar to #1, I don’t recommend this approach.

    Edit:
    4. The user Compo also recommends combining 1 and 2 to launch PS from a batch file in a comment.

    Example: @%SystemRoot%System32WindowsPowerShellv1.0powershell.exe -NoProfile -Command "(Get-Content '.test.json' -Raw | ConvertFrom-Json).data.ip"

    Login or Signup to reply.
  2. Can be done without external tools with jsonextractor.bat :

    jsonextractor.bat demo.json data.ip
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search