【发布时间】:2015-07-18 20:38:43
【问题描述】:
我有一个包含客户列表和日期的 JSON 文件。
文件如下所示:
{
"Customers": [
{
"Customer": "Customer Name Here",
"Company": "Super Coffee",
"First Name": "First Name Here",
"Main Phone": "777-777-7777",
"Fax": "777-777-7777",
"Bill to 1": "Billing Address One",
"Bill to 2": "Billing Address Two",
"Bill to 3": "Billing Address Three",
"Ship to 1": "Shipping Address One",
"Ship to 2": "Shipping Address Two",
"Ship to 3": "Shipping Address Three",
"Customer Type": "Dealer/Retail"
},
{
"Customer": "Customer Name Here",
"Company": "Turtle Mountain Welding",
"First Name": "First Name Here",
"Main Phone": "777-777-7777",
"Fax": "777-777-7777",
"Bill to 1": "Billing Address One",
"Bill to 2": "Billing Address Two",
"Bill to 3": "Billing Address Three",
"Ship to 1": "Shipping Address One",
"Ship to 2": "Shipping Address Two",
"Ship to 3": "Shipping Address Three",
"Customer Type": "Dealer/Retail"
},
{
"Customer": "Customer Name Here",
"Company": "Mountain Equipment Coop",
"First Name": "First Name Here",
"Main Phone": "777-777-7777",
"Fax": "777-777-7777",
"Bill to 1": "Billing Address One",
"Bill to 2": "Billing Address Two",
"Bill to 3": "Billing Address Three",
"Ship to 1": "Shipping Address One",
"Ship to 2": "Shipping Address Two",
"Ship to 3": "Shipping Address Three",
"Customer Type": "Dealer/Retail"
},
{
"Customer": "Customer Name Here",
"Company": "Best Soup Inc.",
"First Name": "First Name Here",
"Main Phone": "777-777-7777",
"Fax": "777-777-7777",
"Bill to 1": "Billing Address One",
"Bill to 2": "Billing Address Two",
"Bill to 3": "Billing Address Three",
"Ship to 1": "Shipping Address One",
"Ship to 2": "Shipping Address Two",
"Ship to 3": "Shipping Address Three",
"Customer Type": "Dealer/Retail"
}
]
}
我需要能够逐块而不是逐行从文件中提取数据。
我习惯于逐行解析文件以获取数据,但是对于 JSON,我需要以某种方式逐块读取它(或者更准确地说,逐个对象?)。我需要为每个客户阅读括号内的内容。这样我就可以编写一个脚本来提取我需要的数据,并从中构建一个 CSV 文件。
例如:
i="1"
for file in *.json; do
customername=$(jsonblock$i:customername);
customerAddress=$(jsonblock$i:customeraddress);
etc...
i=$[i+1]
done
我明白在逐行读取文件时这是如何完成的,但是我怎样才能像读取一行一样读取每个 JSON 块呢?
【问题讨论】:
-
你要求任何语言,只要它解析json?
-
我建议使用令牌...你的 json 文件是偶然的链接吗?
-
这在带有jq 的shell 脚本中很容易做到,除了
jq似乎不处理带有空格的键名。我会使用 Python 而不是用于处理 JSON 文档的 shell 脚本。 -
MAC:我不确定您所说的“您的 json 文件是链接”是什么意思。任何语言都可以。适合工作的工具就是适合工作的工具。
标签: json perl parsing data-structures perl-data-structures