Search code examples
jsonbashsyntax-errorjq

Extract a particular field from json output using jq


I'm working a bash script to extraxt specific field from json output using jq.

USERNAME=$(echo "$OUTPUT" | jq -r '.[] | .name')

Due to jq it always fails with parse error: Invalid numeric literal at line 1, column 2 error.

My restapi result has the below output.

[
  {
    "url": "#/systemadm/groups/uuid-d6e4e05",
    "options": {},
    "group_id": 313,
    "owner": "abc-123-mec",
    "owner_id": "ad1337884",
    "id": "c258d7b330",
    "name": "abc-group"
  },
  {
    "options": {},
    "id": "global%3Regmebers",
    "name": "Udata-123"
  },
  {
    "url": "#/systemadm/groups/uuid-38943000",
    "options": {},
    "group_id": 910,
    "owner": "framework-abcc",
    "owner_id": "78d4472b738bc",
    "id": "38943000057a",
    "name": "def-group"
  },
........................
............................
......................................

So what's wrong with this jq response of code to get "name" ?


Solution

  • jq can only process valid JSON.

    If the value of OUTPUT is literally "id": "c258d7b330","name": "abc-group", then you could enclose it in curly braces to make it valid JSON. No guarantees though; this depends on the exact format of your input.

    OUTPUT='"id": "c258d7b330",
    "name": "abc-group"'
    USERNAME="$(printf '%s\n' "{$OUTPUT}" | jq -r '.name')"
    printf '%s\n' "$USERNAME"; // abc-group
    

    If it cannot be converted to valid JSON, maybe a simple solution using grep+cut or awk would suffice?

    OUTPUT='"id": "c258d7b330",
    "name": "abc-group"'
    USERNAME="$(printf '%s\n' "$OUTPUT" | grep '^"name":' | cut -d'"' -f4)"
    

    awk:

    printf '%s\n' "$OUTPUT" | awk -F'"' '/^"name":/{print $4}'
    

    Or even use jq to parse the input as array of strings and then filter for the line in which you are interested:

    jq -Rr '(select(startswith("\"name\":")) / "\"")[3]'
    

    All options are really fragile and I recommend to fix your input to be actual, valid JSON