如何将文本转换为JSON文件?[已关闭]

xxe27gdn  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(95)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
2天前关闭。
Improve this question
我的文本文件包含(作为示例):

study.description = "test description" ;
study.experiment_name = "default" ;
study.assert_handling = 0 ;
study.noheader = NO ;

atmosphere.wind_dir_0 = 0.00000000000000 ;
atmosphere.wind_dir_1 = 0.00000000000000 ;
atmosphere.alt_high = 600.00000000000000 ;
atmosphere.alt_low = 6.00000000000000 ;

我累了:

json_object = json.loads(line)

并且:

command, description = line.strip().split(None, 1)

dict1[command] = description.strip()

out_file = open("test1.json", "w")
json.dump(dict1, out_file, indent = 4, sort_keys = False)

我想要的东西像:

{"study": {
  "description": "test description",
  "experiment_name": "default",
  "assert_handling": 0,
  "noheader": "NO"
}}
{"atmosphere": {
  "wind_dir_0": 0.0,
  "wind_dir_1": 0.0,
  "alt_high": 600.0,
  "alt_low": 6.0
}}
yeotifhr

yeotifhr1#

你可以使用这个代码:

dict = {}
for x in study.__dict__.keys():
   if not x.startswith('_'):
      dict[x] = getattr(study, x)

最后将dict转储到json文件中

相关问题