正在try 将CSV文件转换为JSON

Here is two sample lines :

-21.3214077;55.4851413;Ruizia cordata
-21.3213078;55.4849803;Cossinia pinnata

我想要一些类似的东西:

"occurrences": [
                 {
                "position": [-21.3214077, 55.4851413],
                "taxo": {
                    "espece": "Ruizia cordata"
                 },
                 ...
             }]

Here is my script :

    echo '"occurences": [ '

cat se.csv | while read -r line
  do
      IFS=';' read -r -a array <<< $line;
      echo -n -e '{ "position": [' ${array[0]}
      echo -n -e ',' ${array[1]} ']'
      echo -e ', "taxo": {"espece":"' ${array[2]} '"'
done
echo "]";

我得到了非常奇怪的结果:

   "occurences": [ 
 ""position": [ -21.3214077, 55.4851413 ], "taxo": {"espece":" Ruizia cordata
 ""position": [ -21.3213078, 55.4849803 ], "taxo": {"espece":" Cossinia pinnata

我的代码有什么问题?

推荐答案

The right tool for this job is jq.

jq -Rsn '
  {"occurrences":
    [inputs
     | . / "\n"
     | (.[] | select(length > 0) | . / ";") as $input
     | {"position": [$input[0], $input[1]], "taxo": {"espece": $input[2]}}]}
' <se.csv

emits, given your input:

{
  "occurences": [
    {
      "position": [
        "-21.3214077",
        "55.4851413"
      ],
      "taxo": {
        "espece": "Ruizia cordata"
      }
    },
    {
      "position": [
        "-21.3213078",
        "55.4849803"
      ],
      "taxo": {
        "espece": "Cossinia pinnata"
      }
    }
  ]
}

顺便说一下,您的原始脚本的错误较少的版本可能如下所示:

#!/usr/bin/env bash

items=( )
while IFS=';' read -r lat long pos _; do
  printf -v item '{ "position": [%s, %s], "taxo": {"espece": "%s"}}' "$lat" "$long" "$pos"
  items+=( "$item" )
done <se.csv

IFS=','
printf '{"occurrences": [%s]}\n' "${items[*]}"

注:

  • 使用cat将管道引入一个回路(和good reasons not to)是绝对没有意义的;因此,我们使用重定向(<)将文件直接作为循环的stdin打开.
  • 可以向read传递目标变量列表;因此不需要读入数组(或first读入字符串,然后生成Heresting并从中读入数组).末尾的_确保丢弃多余的列(通过将它们放入名为_的伪变量中),而不是附加到pos.
  • "${array[*]}" generates a string by concatenating elements of array with the character in IFS; we can thus use this to ensure that commas are present in the output only when they're needed.
  • printf优先于echo使用,如the specification for echo itself的应用程序使用部分所建议.
  • 由于它是通过字符串连接生成JSON的,因此它本身仍然存在缺陷.不要用它.

Json相关问答推荐

从Razor Pages的AJAX Json呈现DataTables问题.Net GET

使用Jolt将字符串数组转换为JSON对象数组

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

为什么JQ筛选器不将原始输入打印为$var|.';文档?

NiFi QueryRecord处理器- Select 可选的JSON属性

有没有办法让serde_json正确/不正确地处理NaN、inf和-inf(IEEE 754特殊标准)?

XSLT 3.0 Json-to-xml,json 包含 html struct

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

如何在 Android Studio 中将 List 字段作为空列表[]返回?

使用 System.Text.Json 序列化记录成员

Golang / Go - 如果 struct 没有字段,如何将其编组为空?

解析包含换行符的 JSON

如何在 Perl 中将简单的哈希转换为 json?

Peewee 模型转 JSON

将 json 转换为 C# 数组?

FastAPI:如何将正文读取为任何有效的 json?

为什么 RestTemplate 不将响应表示绑定到 PagedResources?

用 JSON 编写 HTML 字符串

在rails中将JSON字符串转换为JSON数组?

如何在预先存在的 SQL 数据库之上使用 Elastic Search?