Home > Back-end >  Is there any way to iterate a JSON object that has arrays and find key inside that array on a batch
Is there any way to iterate a JSON object that has arrays and find key inside that array on a batch

Time:06-13

I'm coding a cmd batch script that contians a function to iterate a json file containing multiple json arrays to find a key and its value. The json object does look like the next example:

{
    "array1": [{ "1": "xx"}, { "2": "zz"},{ "3": "zz"}, {"4": "xx"}],
    "array2": [{ "1": "xx"}, { "2": "zz"},{ "3": "zz"}, {"4": "xx"}]
}

I have tried to use json_extractor.bat, jq and other alternatives that I found on StackOverflow but no way to iterate through an array.

In my case to help with this problem to find the json key I have the array variable name and the key name.

Thanks for the help!

Edit: Im provided with the array name, for example, it would be "array1", also with the json key of the variable, for example array1["1"], that would retrieve me "xx" value.

CodePudding user response:

Using jq and the example given in the update, you might wish to consider:

jq --arg a "array1" --arg k "1" -r '.[$a][][$k]//empty' 

or something similar, depending on your detailed requirements.

CodePudding user response:

You should not process Json files via Batch files. Any change in the input file will make the Batch file fail. However, if you are sure that the format of the input file is always the same, then the code below solve your problem:

@echo off
setlocal EnableDelayedExpansion

for /F "tokens=1* delims=: " %%a in (test.txt) do (
   set "values=%%b"
   if defined values (
      set "values=!values: =!"
      set ^"values=!values:},{=^
%do not remove this line%
!^"
      for /F "tokens=1,2 delims=:{}[]" %%x in ("!values!") do set "%%~a[%%x]=%%y"
   )
)

SET ARRAY

Output:

array1["1"]="xx"
array1["2"]="zz"
array1["3"]="zz"
array1["4"]="xx"
array2["1"]="xx"
array2["2"]="zz"
array2["3"]="zz"
array2["4"]="xx"
  • Related