编辑JSON文件,同时保持格式正确(例如缩进)

2024-10-01 00:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON文件,格式如下,我想要一个方法来轻松编辑两个数据集中的数据

通过在.txt或.xls文件中插入表(每个表有2列),如何轻松替换这两个数据表[x,x]

我曾尝试在MATLAB中使用jsondecode和JSONECODE函数来实现这一点,但当我重写到.json文件时,所有标识和行更改都丢失了。如何(以及使用哪种软件)使其保持正确的格式

{
  "Compounds" :
      [ "frutafresca" ],
  "Property 1" : 
      {
      "Scheme" : "Test1"  ,
      "StdValue"  : 0.01                 ,
      "Data":
          [
            [     353.15  ,   108320   ],
            [   503.15  ,   5120000  ],
            [   513.15  ,   6071400  ]
          ]
      },
  "Property 2" : 
      {
      "Scheme" : "Test 1"  ,
      "StdValue"  : 0.01                 ,
      "Data":
          [
            [     273.15  ,   806.25 ],
            [   283.15  ,   797.92 ],
            [   293.15  ,   789.39 ],
            [   453.15  ,   598.39 ],
            [   463.15  ,   578.21 ],
            [   473.15  ,   556.79 ]
          ]
      }
}

Tags: 文件数据方法txtjson编辑data格式
1条回答
网友
1楼 · 发布于 2024-10-01 00:24:28

是否有理由不使用标准libjson模块

json模块

docs开始:

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)

If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "\t"), that string is used to indent each level.

import json

data = None
with open('data.json', 'r') as _file:
    data = json.load(_file)
assert data is not None


## do your changes to data dict


with open('data.json', 'w') as _file:
    json.dump(data, _file, indent=2)    ## indent output with 2 spaces per level

相关问题 更多 >