简体   繁体   English

在shell脚本中读取JSON数据

[英]Reading JSON data in a shell script

I have a JSON file containing data about some images: 我有一个JSON文件,其中包含有关某些图像的数据:

{
    "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. 我希望在shell脚本中以简单的方式处理这些值。 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. 我正在使用convert(Imagemagick)来处理图像。 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 : 从json文件中的一行读取条目说裁剪,然后在裁剪图像时使用该值:

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 convert -crop [来自json的图像宽度] x [来自json的图像高度] +0 + [来自json的裁剪值] [来自json的session_id] - 来自json的[imageID] .png [sessionID] - [ImageID] -cropped.png

I would recommend using jq . 我建议使用jq For example, to get the imageHeight , you can use: 例如,要获取imageHeight ,您可以使用:

jq ".imageHeight" data.json

Output: 输出:

1536

If you want to store the value in a shell variable use: 如果要将值存储在shell变量中,请使用:

variable_name=$(jq ".imageHeight" data.json)

Python-solution Python的解决方案

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM