1

I have a JSON file containing data about some images:

{
    "imageHeight": 1536,
    "sessionID": "4340cc80cb532ecf106a7077fc2a166cb84e2c21",
    "bottomHeight": 1536,
    "imageID": 1,
    "crops": 0,
    "viewPortHeight": 1296,
    "imageWidth": 2048,
    "topHeight": 194,
    "totalHeight": 4234
}

I wish to process these values in a simple manner in a shell script. I searched online but was not able to find any simple material to understand.

EDIT : What I wish to do with the values ?

I'm using convert (Imagemagick) to process the images. So, the whole workflow is something like. Read the an entry say crop from a line in the json file and then use the value in cropping the image :

convert -crop [image width from json]x[image height from json]+0+[crop value from json] [session_id from json]-[imageID from json].png [sessionID]-[ImageID]-cropped.png

10
  • 1
    I highly rate jq for working with JSON in a shell: stedolan.github.io/jq Commented Jun 25, 2014 at 10:56
  • Is using python or perl an option? They both have very good support for working with json-files. json-support is not supported natively in either awk, grep or shell. Commented Jun 25, 2014 at 10:56
  • You may provide solutions in python also , it might be helpful :) Commented Jun 25, 2014 at 10:57
  • ...also, what would you like to do with the values, i.e. what is your expected outcome? Please update your question. Right now we are just guessing. Commented Jun 25, 2014 at 10:57
  • @cbuckley Please can you provide an example on how to process a field in a line in the json file Commented Jun 25, 2014 at 10:58

2 Answers 2

2

I would recommend using jq. For example, to get the imageHeight, you can use:

jq ".imageHeight" data.json

Output:

1536

If you want to store the value in a shell variable use:

variable_name=$(jq ".imageHeight" data.json)
Sign up to request clarification or add additional context in comments.

Comments

1

Python-solution

import json
from pprint import pprint
json_data=open('json_file')
data = json.load(json_data)
pprint(data)
data['bottomHeight']

output:

In [28]: pprint(data)
{u'bottomHeight': 1536,
 u'crops': 0,
 u'imageHeight': 1536,
 u'imageID': 1,
 u'imageWidth': 2048,
 u'sessionID': u'4340cc80cb532ecf106a7077fc2a166cb84e2c21',
 u'topHeight': 194,
 u'totalHeight': 4234,
 u'viewPortHeight': 1296}

In [29]: data['bottomHeight']
Out[29]: 1536

Comments

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.