gpt4 book ai didi

用于过滤 JSON 对象中包含特定值的数组的 Python 脚本

转载 作者:行者123 更新时间:2023-11-30 22:51:00 25 4
gpt4 key购买 nike

我有一个 json 对象,它由一个带有键“data”的对象组成,该对象的值列在一组数组中。我需要返回包含值 x 的所有数组,但数组本身没有键。我正在尝试编写一个脚本来输入源文件(inFile)并定义导出文件(outFile)。这是我的数据结构:

{ "data": [
["x", 1, 4, 6, 2, 7],
["y", 3, 2, 5, 8, 4],
["z", 5, 2, 5, 9, 9],
["x", 3, 7, 2, 6, 8]
]
}

这是我当前的脚本:

import json

def jsonFilter( inFile, outFile ):
out = None;

with open( inFile, 'r') as jsonFile:
d = json.loads(json_data)
a = d['data']
b = [b for b in a if b != 'x' ]
del b
out = a


if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );

else:
print "Error creating new jsonFile!"

解决方案

感谢 Rob 和大家的帮助!这是最终的工作命令行工具。这需要两个参数:inFile 和 Outfile。 ~$ python jsonFilter.py inFile.json outFile.json

import json

def jsonFilter( inFile, outFile ):
# make a dictionary.
out = {};

with open( inFile, 'r') as jsonFile:
json_data = jsonFile.read()
d = json.loads(json_data)
# build the data you want to save to look like the original
# by taking the data in the d['data'] element filtering what you want
# elements where b[0] is 'x'
out['data'] = [b for b in d['data'] if b[0] == 'x' ]


if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );

else:
print "Error creating new JSON file!"

if __name__ == "__main__":
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('inFile', nargs=1, help="Choose the in file to use")
parser.add_argument('outFile', nargs=1, help="Choose the out file to use")
args = parser.parse_args()
jsonFilter( args.inFile[0] , args.outFile[0] );

最佳答案

第一个问题,查询字符串对于所有内容都是正确的(也称为返回整个数据集,因为您正在将 b(列表)与“x”字符串进行比较

  b = [b for b in a if b != 'x' ]

你想做的是:

  b = [b for b in a if b[0] != 'x' ]

第二个问题是您试图通过查询和删除结果来删除数据。由于结果包含一个副本,不会从原始容器中删除任何内容。
相反,仅使用您想要的元素构建新数据,然后保存它们。此外,您没有在输出数据中重新创建“data”元素,因此输出的 json 具有与输入数据相同的结构。

import json

def jsonFilter( inFile, outFile ):
# make a dictionary instead.
out = {};

with open( inFile, 'r') as jsonFile:
json_data = jsonFile.read()
d = json.loads(json_data)
# build the data you want to save to look like the original
# by taking the data in the d['data'] element filtering what you want
# elements where b[0] is 'x'
out['data'] = [b for b in d['data'] if b[0] == 'x' ]


if out:
with open( outFile, 'w' ) as jsonFile:
jsonFile.write( json.dumps( out ) );

else:
print "Error creating new jsonFile!"

输出 json 数据如下所示:

 '{"data": [["x", 1, 4, 6, 2, 7], ["x", 3, 7, 2, 6, 8]]}'

如果您不希望输出包含“data”根元素,而只是包含与过滤器匹配的数据数组,则更改该行:

 out['data'] = [b for b in d['data'] if b[0] == 'x' ]

 out = [b for b in d['data'] if b[0] == 'x' ]

经过此更改,输出 json 数据如下所示:

 '[["x", 1, 4, 6, 2, 7], ["x", 3, 7, 2, 6, 8]]'

关于用于过滤 JSON 对象中包含特定值的数组的 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com