如何在python中进行JSON模式转换? 我知道Jolt服务于此目的,但它是用Java编写的。 我有2个JSON对象,一个是输入,第二个是映射器。我试图通过遍历2个json对象并应用转换来实现它。但是,我不确定它是否是一种有效的方式。
以下是一个例子:
输入
{
"name": "Bob Odenkirk",
"title": "Software Engineer",
"location": {
"locality": "San Francisco",
"region": "CA",
"country": "United States"
},
"age": 62,
"status": "Active"
}
输出
{
"names": ["Bob Odenkirk"],
"occupations": ["Software Engineer"],
"locations": ["San Francisco, CA"]
}
答案 0 :(得分:3)
听起来像你的需要可以用jq完成。有python绑定,请参阅this question。
但是不知道你的输入和输出格式,不能说jq是你的最佳选择。
使用pyjq
import json
import pyjq
json_input = json.loads("""{
"name": "Bob Odenkirk",
"title": "Software Engineer",
"location": {
"locality": "San Francisco",
"region": "CA",
"country": "United States"
},
"age": 62,
"status": "Active"
}""")
r = pyjq.one(
'{names: [.name], occupations: [.title], locations: [.location.locality + ", " + .location.region]}',
json_input,
)
print(json.dumps(r, indent=4))
的产率:
{
"names": [
"Bob Odenkirk"
],
"occupations": [
"Software Engineer"
],
"locations": [
"San Francisco, CA"
]
}