Fix jq Cannot Index String with String Errors
Cannot index string with string "name" means jq tried to read .name from a string, not an object. Check the type of the value immediately before .name; the fix depends on whether you selected a string from an array or received JSON encoded inside a string.
The array contains strings, not objects
Input:
{"users":["Ada","Bo"]}
This filter treats every array element as an object:
.users[] | .name
It fails on the first element:
jq: error (at <stdin>:1): Cannot index string with string "name"
Reproduce the indexing error in the jq playground
Inspect the values produced before .name:
.users[] | type
Output:
"string"
"string"
Inspect the selected values in the jq playground
.users is an array, but .users[] produces its individual strings. If those strings are the names you want, remove the object lookup:
.users[]
Output (two jq results):
"Ada"
"Bo"
Run the corrected selection in the jq playground
If you actually expect objects such as {"users":[{"name":"Ada"},{"name":"Bo"}]}, fix the input or choose the correct array before using .users[] | .name. Do not add fromjson to ordinary name strings.
The field is JSON text, not a JSON object
Input:
{"payload":"{\"name\":\"Ada\"}"}
The outer document is valid JSON, but payload is a string containing another JSON document. .payload.name fails with the same Cannot index string with string "name" error.
Reproduce the payload error in the jq playground
Check .payload | type: the output is "string", not "object". Here, only if the field really contains valid JSON text, parse that string before indexing:
.payload | fromjson | .name
Output:
"Ada"
Run the parsed-payload fix in the jq playground
fromjson fails on ordinary text that is not valid JSON. If the input instead has an actual object, {"payload":{"name":"Ada"}}, use .payload.name directly and do not parse it twice. Inspect the value at the failing step rather than guessing from the outer document's shape.
These filters and errors were checked with jq 1.7.1, jq 1.8.1, and the browser jq playground. For absent keys versus explicit null, see check whether a key exists; for supplying typed JSON from a shell, see pass values with --argjson and the jq cheatsheet. Reference: jq manual, type and fromjson.