GavinD
GavinD

Reputation: 25

jq-win64.exe: Parsing data from a JSON file in Windows Batch File

I have the following JSON file (song.json) that contains:

{
  "Result": [
    {
      "ItemTitle": "Sometimes It Hurts",
      "Artists": [
        "Voost"
      ],
      "MediaEnd": "00:02:15.8490000",
      "Extro": "00:02:12.8200000",
      "MediaId": 9551,
      "ActualLength": "00:02:12.8200000",
      "ItemType": "Song"
    },
    {
      "ItemTitle": "Been a Long Time (Full Intention 2021 Remix)",
      "Artists": [
        "The Fog"
      ],
      "MediaEnd": "00:03:11.3170000",
      "IntroEnd": "00:00:07.4700000",
      "Extro": "00:03:08.6300000",
      "MediaId": 9489,
      "ActualLength": "00:03:08.6300000",
      "ItemType": "Song"
    }
  ],
  "ExceptionMessage": null,
  "FailMessage": null,
  "ExceptionTypeName": null
}

I want to extract the first “ItemTitle” and the first “Artist” and save them as variables.

In this example the result I am looking for would be:

ItemTitle=Sometimes It Hurts

Artist=Voost

I have been trying to use jq-win64.exe as this needs to run in a Windows Batch File, but I can’t get the syntax right. I have tried various examples that I have found on here but none of them appears to work as required. Can anyone suggest a solution?

Upvotes: 1

Views: 2078

Answers (1)

peak
peak

Reputation: 116880

First things first.

Since you seem to be having trouble on several fronts , I would suggest that you first get your jq query working the way you want by using jq with the -f command-line option. That way, you can write your query without having to worry about Windows rules for escaping characters on the command line. When the results are as you wish, you might even to decide to leave well-enough alone.

Next, to obtain the values you want, it would seem you will want a jq query like this:

.Result | first(.[].ItemTitle), first(.[].Artists[])

With your JSON, this produces:

Sometimes It Hurts
Voost

But you say you want these values in the KEY=VALUE form. This can be achieved by modifying the basic query, e.g. as follows:

.Result|"ItemTitle=\(first(.[].ItemTitle))", "Artist=\(first(.[].Artists[]))"

Somehow I doubt this is really what you want, but the rest should be clear sailing.

Upvotes: 0

Related Questions