skip to Main Content

There are json file with variable quantity of elements describing the keywords. The following is the typical example:

{"keywords":[{"keyword":"halloween","score":0.9621220167107003},
{"keyword":"pumpkin","score":0.9527655356551675},
{"keyword":"nature","score":0.8530320061364176},
{"keyword":"animal","score":0.7936456829239327}],"status":"ok"}

The script should parce this json and I need to get a line with keywords formatted as following:

,,,"halloween,pumpkin,nature,animal"

As I already stated, the number of entries may be different. From 10 to 100, for example.

Honestly, I am stuck with that task. Would anyone help me please?

setlocal enabledelayedexpansion
  set keywords=""

  rem Loop through each line of the keywords.txt file
  for /f "skip=1 tokens=2 delims={" %%b in (keywords.txt) do (
    rem Extract the keyword from the current line
    set keyword=%%b
    set keyword=!keyword:"keyword":"!
    set keyword=!keyword:",score":!
    set keyword=!keyword:,!

    rem Add the keyword to the keywords variable
    set keywords=!keywords!,!keyword!
  )

But it doesn’t help anything

4

Answers


  1. @ECHO OFF
    SETLOCAL ENABLEDELAYEDEXPANSION
    rem The following settings for the source directory and filename are names
    rem that I use for testing and deliberately include names which include spaces to make sure
    rem that the process works using such names. These will need to be changed to suit your situation.
    
    SET "sourcedir=u:your files"
    SET "filename1=%sourcedir%q75438837.txt"
    
    SET "words="
    SET "snagnext="
    
    FOR /f "usebackqdelims=" %%e IN ("%filename1%") DO (
     SET "LINE=%%e"
     FOR %%y IN ({ } [ ] :) DO SET "line=!line:%%y=,!"
     FOR %%y IN (!line!) DO (
      IF DEFINED snagnext SET "words=!words!,%%~y"
      SET "snagnext="
      IF "%%~y"=="keyword" SET "snagnext=Y"
     )
    )
    SET "words=%words:~1%"
    SET words
    GOTO :EOF
    

    Note that if the filename does not contain separators like spaces, then both usebackq and the quotes around %filename1% can be omitted.

    Read each line; replace each colon and various brackets with commas. The result is a simple comma-separated list in line. Some elements may be quoted.

    Use a simple for to iterate through all of the elements on each line. If the element stripped of quotes and requoted is "keyword" then set the snagnext flag to y.

    The next element to appear when snagnext is defined gets accumulated into the words list.

    Tip: Use set "var=value" for setting string values – this avoids problems caused by trailing spaces. Don’t assign " or a terminal backslash or Space. Build pathnames from the elements – counterintuitively, it is likely to make the process easier. If the syntax set var="value" is used, then the quotes become part of the value assigned.

    Login or Signup to reply.
  2. For parsing JSON, use the help of PowerShell:

    Here’s a simple one line example:

    @%SystemRoot%System32WindowsPowerShellv1.0powershell.exe -NoProfile ',,,"""' + $((Get-Content 'keywords.txt' -Raw | ConvertFrom-Json).keywords.keyword -join ',') + '"""'& Pause
    
    Login or Signup to reply.
  3. This simpler method combine several conversion steps in lesser commands, so it is more efficient and run faster:

    @echo off
    setlocal EnableDelayedExpansion
    
    set "keywords="
    for /F "delims=," %%a in (keywords.txt) do (
       set "line=%%a"
       for /F "tokens=2 delims=:" %%b in ("!line:*[=!") do set "keywords=!keywords!,%%~b"
    )
    
    echo "!keywords:~1!"
    
    • The first for /F "delims=," command eliminates from first comma to end of line, so it just gets {"keywords":[{"keyword":"halloween" or {"keyword":"pumpkin" in line variable.
    • The "!line:*[=!" part eliminates from beginning of line until first [, if any, so it process only the first line giving {"keyword":"halloween"; that is, the same value of the rest of lines.
    • The for /F "tokens=2 delims=:" command over previous replacement get just the keyword value, like "halloween" or "pumpkin".
    • Finally, the %%~b used to add each keyword eliminate the quotes.
    Login or Signup to reply.
  4. You’ve included the tag , but as Batch doesn’t support JSON at all, I hope you realize that you can’t use it to parse JSON without resorting to fragile hacks.

    I’d recommend you use a dedicated JSON tool instead, like :

    xidel -s "keywords.txt" -e "$json//keyword" --output-separator=,
    xidel -s "keywords.txt" -e "join($json//keyword,',')"
    

    And if you really want the surrounding double-quotes, either of these will do:

    xidel -s "keywords.txt" -e "concat('"',join($json//keyword,','),'"')"
    xidel -s "keywords.txt" -e "'"'||join($json//keyword,',')||'"'"
    xidel -s "keywords.txt" -e "x'"{join($json//keyword,',')}"'"
    

    it is answer of third party site’s API (everypixel.com)

    If it’s simply through a GET- or POST-request (with curl?) how you got this JSON in the first place, then xidel help out as well. No need to save it to a temporary file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search