json转成xml -JSON 转 CSV 再转回来,为什么三个不同的值变成了同一个? - #content_views

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力平台 👁️ 463 次阅读

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */

#content_views .toc,

/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */

#content_views.markdown_views > p:empty:has(+ .toc),

#content_views.markdown_views > .toc + p:empty,

/* 富文本旧版目录标记 */

#content_views.htmledit_views #main-toc,

#content_views.htmledit_views #hr-toc,

#content_views.htmledit_views p[id*="-toc"] {

display: none !important;

}

/* 目录去掉后,紧跟的首个标题不再多出一块上边距 */

#content_views.markdown_views > .toc + h1,

#content_views.markdown_views > .toc + h2,

#content_views.markdown_views > .toc + h3,

#content_views.markdown_views > .toc + h4,

#content_views.markdown_views > .toc + p:empty + h1,

#content_views.markdown_views > .toc + p:empty + h2,

#content_views.markdown_views > .toc + p:empty + h3,

#content_views.markdown_views > .toc + p:empty + h4 {

margin-top: 0 !important;

}

JSON 转 CSV 再转回来,为什么三个不同的值变成了同一个?

我用 jsonformat 转一批测试数据:有的记录没传备注,有的明确传了 null,还有的备注就是空字符串。CSV 打开一眼看过去,没毛病。再转回 JSON,三条记录却都多了一个 "note": ""。

如果只是给人看表格,这没什么。但如果这张表还要导回后台,差别就大了。以批量更新为例,约定可以是:没传字段就保留旧值,传 null 就清空,传空字符串就存空文本。 三者一旦变成同一种值,导入端就没办法按原意执行。

一、用四条记录复现

[

{"id": 1},

{"id": 2, "note": null},

{"id": 3, "note": ""},

{"id": 4, "note": "null"}

]

把它放进「JSON 转 CSV」,再用逗号分隔、首行作表头转回来。在下面链接固定的源码版本上,用 Node 加最小 DOM 桩直接调用两个按钮回调,得到的 CSV 是:

id,note

1,

2,

3,

4,null

转换回来的结果:

[

{"id": "1", "note": ""},

{"id": "2", "note": ""},

{"id": "3", "note": ""},

{"id": "4", "note": "null"}

]

第四条是对照组:原来的 "null" 是四个字符,落到 CSV 后是实际可见的文本。前面三条都变成了空单元格。另外,数字 ID 也变成了字符串。这个实验验证的是仓库里的转换回调,没有做浏览器端到端测试。

二、信息在哪一步丢的?

我会先看导出的原始 CSV,不急着给导入补规则。

JSON → CSV 源码 先从所有记录收集表头,再对每行按表头取值。取不到 note 时得到 undefined;显式 null 和 undefined 都输出空文本,空字符串转换后也还是空文本。

CSV → JSON 源码 按表头把单元格填回对象,缺失的单元格也会补空字符串。导入时已经只看得见三个一样的空格子。就算规定「所有空格子变 null」,也只是换了一种猜法。

三、需要批量回灌,就在 CSV 里留一列状态

两端都归自己控制时,我会把 note 拆成两列:

note_state=missing:原对象不存在 note。note_state=null:原对象明确传了 null。note_state=text:note_value 是字符串,可以为空。

下面是一份独立的 Python 示例,不是 jsonformat 已有功能。它只处理 id 和可选 note,用标准库处理逗号、双引号和跨行文本。遇到陌生字段或状态和值互相矛盾,直接报错,不替业务猜。

import csv

from io import StringIO

HEADER = ["id", "note_state", "note_value"]

def encode(records):

stream = StringIO(newline="")

writer = csv.writer(stream, lineterminator="\r\n")

writer.writerow(HEADER)

for record in records:

if record.keys() - {"id", "note"}:

raise ValueError("只接受 id 和 note,其他字段不会被静默丢弃")

ident = record.get("id")

if not isinstance(ident, str) or ident == "":

raise ValueError("id 必须是非空字符串")

if "note" not in record:

state, value = "missing", ""

elif record["note"] is None:

state, value = "null", ""

elif isinstance(record["note"], str):

state, value = "text", record["note"]

else:

raise ValueError("note 只允许字符串或 null")

writer.writerow([ident, state, value])

return stream.getvalue()

def decode(content):

reader = csv.reader(StringIO(content, newline=""), strict=True)

if next(reader, None) != HEADER:

raise ValueError("表头或传输约定不符")

result = []

for columns in reader:

line = reader.line_num

if len(columns) != len(HEADER):

raise ValueError(f"输入至第 {line} 行:列数不符") 拼多多帮助力入口

ident, state, value = columns

if ident == "":

raise ValueError(f"输入至第 {line} 行:id 不能为空")

record = {"id": ident}

if state == "text":

record["note"] = value

elif state in {"missing", "null"} and value == "":

if state == "null":

record["note"] = None

else:

raise ValueError(f"输入至第 {line} 行:非法字段状态")

result.append(record)

return result

def expect_rejected(content):

try:

decode(content)

except (ValueError, csv.Error) as error:

print(f"正确拒绝:{error}")

else:

raise AssertionError("坏数据被接受了")

if __name__ == "__main__":

original = [

{"id": "001"},

{"id": "002", "note": None},

{"id": "003", "note": ""},

{"id": "004", "note": ' 他说"收到",明天处理\n第二行 '},

{"id": "005", "note": "null"},

]

exported = encode(original)

print(exported, end="")

restored = decode(exported)

assert restored == original

assert "note" not in restored[0]

assert restored[1]["note"] is None

assert restored[2]["note"] == ""

print("往返通过:缺失、null、空字符串仍是三种状态")

expect_rejected("id,note_state,note_value\r\n006,null,不应有内容\r\n")

expect_rejected("id,note_state,note_value\r\n007,text\r\n")

expect_rejected("id,note_state,note_value\r\n008,unknown,\r\n")

保存成 csv_roundtrip.py,运行 python3 csv_roundtrip.py。开头几行如下,最后应看到「往返通过」和三次「正确拒绝」:

id,note_state,note_value

001,missing,

002,null,

003,text,

004,text," 他说""收到"",明天处理

第二行 "

005,text,null

这里的 004 在文本编辑器里占两行,但 CSV 解析器会把带引号的跨行内容当成一条记录。脚本也会检查首尾空格、前导零和字面量 "null" 都没有变。如果要从磁盘读写 CSV,用 encoding="utf-8", newline="" 打开文件,让 CSV 库处理换行。

四、什么时候值得做这一步?

如果用途是预览、发给同事浏览,普通 CSV 就足够。用它做更新导入,先把缺失和清空的行为写进接口约定,再决定是否加状态列。如果文件本来就只在程序间流转,我会优先用 JSON:不用教两端怎么把空单元格翻译回三种意思。

另一个容易漏掉的细节:上面的往返是程序读写测试,不覆盖 Excel 另存后的自动改型。若流程中间有人用表格软件编辑,就拿 001、空字符串和跨行备注再走一遍真实流程。验收问一句:导出后重新导入,字段的意思还一样吗? 这比只看转换按钮有没有变绿实在得多。

项目:Rodert/jsonformat。

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧