- 我可以在Python脚本中执行这个命令吗
可以,使用subprocess。示例:
jsonFile = '/path/to/your/filename.json'
jq_cmd = "/bin/jq '{Name:.name, address:.address[0][1].street}' " + jsonFile
jq_proc = subprocess.Popen(jq_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
jDict = json.loads(jq_proc.stdout.read())
jq_proc.stdout.close()
- 如果可以实现,那么如何循环遍历上面给出的样本数据中嵌套数组元素(address[][].street)?
看到几个记录的JSON数据集会有所帮助。在Python中使用jq循环遍历JSON集合时,很容易获得对象的计数,然后进行迭代。这会增加一些开销,但使代码易于理解。
jq_cmd = "/bin/jq '. | length' " + jsonFile
jq_proc = subprocess.Popen(jq_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
jObjCount = int(jq_proc.stdout.read())
jq_proc.stdout.close()
for ix in range(jObjCount):
jq_cmd = "jq '. | .[" + str(ix) + "]' " + jsonFile
jq_proc = subprocess.Popen(jq_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
jDict = json.loads(jq_proc.stdout.read())
jq_cmd = "/bin/jq '. | .[" + str(ix) + "].sub_Item_Key | length' " + jsonFile
jq_proc = subprocess.Popen(jq_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
jItemCount = int(jq_proc.stdout.read())
jq_proc.stdout.close()
for jx in range(jItemCount):
jq_cmd = "/bin/jq '. | .[" + str(ix) + "].sub_Item_Key[" + str(jx) + "]' " + jsonFile
jq_proc = subprocess.Popen(jq_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
jItemDict = json.loads(jq_proc.stdout.read())
享受吧!
jq
(使用subprocess
模块)。 2- 要从 JSON 中提取数据,请在 Python 中使用json
模块(无需运行任何 shell 命令)。提供示例 JSON 输入和所需输出以及实际得到的输出。 - jfs