1

I'm having trouble parsing this json, which contains an array as its outermost element:

response=[ { "__type": "File", "name": "...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg", "url": "http://files.parse.com/ac3f079b-cacb-49e9-bd74-8325f993f308/...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg" } ]

for blob in $response
do
    url=$(echo $blob | json url)
done

But this last json parsing gives a bunch of errors:

json: error: input is not JSON: Bad object at line 2, column 1:

    ^

Do I need to do something special to turn a JSON array into a bash array, or vice versa?

3
  • 1
    Please provide a runnable example that demonstrates your error. Commented Jul 11, 2014 at 14:34
  • Is that the string that you're actually injecting to the json tool? Perhaps show the code that generates the response? Commented Jul 11, 2014 at 14:48
  • @chepner edited, should be standalone runnable now and produces the error. Commented Jul 11, 2014 at 22:56

2 Answers 2

3

You should quote the value of reponse to protect it from the shell trying to interpret it:

response='[ { "__type": "File", "name": "...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg", "url": "http://files.parse.com/ac3f079b-cacb-49e9-bd74-8325f993f308/...tfss-ea51ec70-d3a8-45e5-abbf-294f2c2c81f0-myPicture.jpg" } ]'

And you can't expect the shell to be able to parse JSON, so for blob in $response isn't going to work out. According to http://trentm.com/json/, using -a should handle the array:

while read url ; do
   # use $url here...
done < <(echo "$response" | json -a url)
Sign up to request clarification or add additional context in comments.

Comments

0

After putting your json in a file and piping it through jsontool it works just fine, so I'm guessing your file has some weird whitespace which is breaking in jsontool.

Try this instead:

cat your_file.json | sed 's/[[:space:]]\+$//' | json

1 Comment

Of course, a proper JSON parser should ignore whitespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.