Home > Net >  How to find and display information from json file with user input via batch command?
How to find and display information from json file with user input via batch command?

Time:12-02

I have a json file (API.json) which looks like this:

{"applist":{"apps":[{"appid":1234567,"name":"Test$: Number 1"},{"appid":7654321,"name":"Test- Number 2"},{"appid":7777777,"name":"Test & *(test)* Num. 3"}]}}

This is just the short version for testing.

I would like to know if it's possible to search for a "name" and view the related "appid" before that "name" via batch or any windows built-in commands.

E.g.

set /P name=Insert the name: 
rem (Part of the name which matches exactly with the name)
if %name%=Test$: echo
Name: Test$: Number 1
App ID: 1234567
rem (Part of the name which matches with more than 1 name)
if %name%=Number echo
Name: Test$: Number 1
App ID: 1234567
Name: Test- Number 2
App ID: 7654321

As it is obvious, Test or Number might, or might not be, included in the name.

I have tried converting this to object via PowerShell (convertto-json) but without any success. I Don't know if that would help.

CodePudding user response:

With jq this task can be solved:

NAME='Test & *(test)* Num. 3'
jq --arg name "$NAME" '.applist.apps[] | select(.name == $name) | .appid' API.json

Output

7777777

CodePudding user response:

This should work:

@echo off
setlocal EnableDelayedExpansion

set /P "=Loading data, please wait." < NUL
call :loadData < API.json
echo/

:nextName
echo/
set "name="
set /P "name=Insert the name: "
if not defined name goto :EOF
set "$!name!" 2>NUL
goto nextName


:loadData

set /P "line="
set /P "next="
for /F "tokens=1* delims=}" %%a in ("!next!") do (
   set "line=!line:*[{={!%%a}"
   set "next=%%b"
)

set "EOF="
:nextLine

set /P "=." < NUL > CON
for %%n in (^"^
%Do not remove this line%
^") do for /F "delims=" %%a in ("!line:},{=}%%~n{!") do (
   for /F "tokens=2,4 delims={:,}" %%x in ("%%a") do (
      if "%%~y" neq "" set "$%%~y=%%~x"
   )
)

if defined EOF exit /B

set "line=!next:~1!"
set /P "next="
if "!next:~-3!" equ "]}}" (
   set "next=!next:~0,-3!"
   set "EOF=1"
)

for /F "tokens=1* delims=}" %%a in ("!next!") do (
   set "line=!line!%%a}"
   set "next=%%b"
)

goto nextLine

IMPORTANT:

  • This program may fail for anyone of several causes
  • This program may take too long
  • This program fail in the fields that include an exclamation-mark. This can be fixed, but the program would take even longer...
  • The "name" consults just match names that start with the given data

Please, report the result

  • Related