如何在没有JSONArray的情况下将CSV转换为JSON?

时间:2017-01-06 00:36:08

标签: json csv converter

我有一个看起来像这样的CSV(下面是标题栏和一个样本行)。

UID MSA Latitude Longitude
1   New York-Newark-Jersey City, NY-NJ-PA   40.7127837  -74.0059413

我想将其转换为JSON。像this这样的网站对我不起作用,因为它们将它转换为JSON数组。相反,我想要的是一系列由UID标题的JSON对象。这看起来如下所示(假装第二个对象的数据与第一个不同)。

[
"1" : {
"Latitude" : 40.7127837,
"Longitude" : -74.0059413,
"MSA" : "New York-Newark-Jersey City, NY-NJ-PA"
},
 "2" : {
"Latitude" : 40.7127837,
"Longitude" : -74.0059413,
"MSA" : "New York-Newark-Jersey City, NY-NJ-PA"
}
]

那里有工具可以帮我吗?我可以编写一个可以执行此操作的脚本,但我不想这样做。

2 个答案:

答案 0 :(得分:1)

您的问题并不表示您正在寻找自动执行此过程的方法。

This site可能会提供您所需要的内容。您需要为输出格式选择JSON-Dictionary。

UID MSA LATITUDE    LONGITUDE
1   New York-Newark-Jersey City, NY-NJ-PA   40.7127837  -74.0059413
2   Seattle, WA 47.6062 122.3321
3   San Francisco, CA   37.7749 122.4194
4   Savannah, GA    32.0835 81.0998


Output:
{
  "1": { "MSA":"New York-Newark-Jersey City, NY-NJ-PA", "LATITUDE":40.7127837, "LONGITUDE":-74.0059413},
  "2": { "MSA":"Seattle, WA", "LATITUDE":47.6062, "LONGITUDE":122.3321},
  "3": { "MSA":"San Francisco, CA", "LATITUDE":37.7749, "LONGITUDE":122.4194},
  "4": { "MSA":"Savannah, GA", "LATITUDE":32.0835, "LONGITUDE":81.0998}
}

你可以在这里下载:test.csv我曾经测试过。

答案 1 :(得分:1)

以下是使用jq的解决方案。

如果filter.jq包含以下过滤器

def parse:
  [
      split("\n")[]           # split string into lines
    | split("\t")             # split into columns
    | select(length>0)        # eliminate blanks
  ]
;
def makeobj($headers;$data):
  [                           # e.g.
      [$headers, $data]       # [["MSA","LATITUDE","LONGITUDE"],["Savannah, GA"...
    | transpose[]             # ["MSA","Savannah, GA"], ["LATITUDE","32.0835"] ...
    | {key:.[0], value:.[1]}  # {"key":"MSA","value":"Savannah, GA"} ...
  ] | from_entries            # {"MSA":"Savannah, GA","LATITUDE":"32.0835",...
  | .LATITUDE  |= tonumber
  | .LONGITUDE |= tonumber
;
def reorganize:
    .[0] as $h                # save headers
  | reduce .[1:][] as $r (    # construct final object result
    {}
    ; .[$r[0]] = makeobj($h[1:]; $r[1:])
    )
;
parse | reorganize

data包含以制表符分隔的

UID MSA LATITUDE    LONGITUDE
1   New York-Newark-Jersey City, NY-NJ-PA   40.7127837  -74.0059413
2   Seattle, WA 47.6062 122.3321
3   San Francisco, CA   37.7749 122.4194
4   Savannah, GA    32.0835 81.0998

然后命令

$ jq -M -Rsr -f filter.jq data

产生

{
  "1": {
    "MSA": "New York-Newark-Jersey City, NY-NJ-PA",
    "LATITUDE": 40.7127837,
    "LONGITUDE": -74.0059413
  },
  "2": {
    "MSA": "Seattle, WA",
    "LATITUDE": 47.6062,
    "LONGITUDE": 122.3321
  },
  "3": {
    "MSA": "San Francisco, CA",
    "LATITUDE": 37.7749,
    "LONGITUDE": 122.4194
  },
  "4": {
    "MSA": "Savannah, GA",
    "LATITUDE": 32.0835,
    "LONGITUDE": 81.0998
  }
}