使用 Python 将值插入 json 文件中的特定位置

Inserting values into specific locations in a json file with Python

试图找到一种优雅的方式将 os.walk() 循环中的文件名插入 特定的 子元素(因为需要更好的术语)在 Python 对象,将输出为 JSON 文件。如果这没有多大意义,这里是我到目前为止拼凑的一些视觉输出。

使用的代码:

import os
from os.path import normpath, basename
import json

ROOT_PATH = "sounds/"
jsonObject = []

for path, subdirs, files in os.walk(ROOT_PATH):
   if files:
      elementId = basename(normpath(path)) + "Audio" # <-- builds custom Id based on path
      jsonObject.append( { "elementId" : elementId, "params" : { "audioPath" : path, "sounds" : [] } } )
      for name in files:
         jsonObject.append(name)  #  <-- problem lies here...

with open('sounds/Elements.json', 'w') as outfile:
   json.dump(jsonObject, outfile, indent=3, ensure_ascii=False, sort_keys=True)

...产生:

[
   {
      "elementId": "soundsAudio",
      "params": {
         "audioPath": "sounds/",
         "sounds": []
      }
   },
   "beep2.mp3",
   "heart_rate_flatline.mp3",
   "shhh.mp3",
   {
      "elementId": "aha_aedAudio",
      "params": {
         "audioPath": "sounds/aha_aed",
         "sounds": []
      }
   },
   "AnalyzingHeartRhythm.mp3",
   "AttachPadsToPatientsBareChest.mp3",
   "BeginCPR.mp3",
   "Charging.mp3",
   "DoNotTouchThePatient.mp3"
]

...这真的很接近。但是我 运行 进入了一个大脑块,将 mp3 文件列表 放入 sounds 部分,因此它看起来像这样:

[
   {
      "elementId": "soundsAudio",
      "params": {
         "audioPath": "sounds/",
         "sounds": [ "beep2.mp3",
                     "heart_rate_flatline.mp3",
                     "shhh.mp3"
         ]
      }
   },
   {
      "elementId": "aha_aedAudio",
      "params": {
         "audioPath": "sounds/aha_aed",
         "sounds": [ "AnalyzingHeartRhythm.mp3",
                     "AttachPadsToPatientsBareChest.mp3",
                     "BeginCPR.mp3",
                     "Charging.mp3",
                     "DoNotTouchThePatient.mp3"
         ]
      }
   }
]

.append.extend.insert 在这一点上让我失望(或者我没有正确使用它们),并进行了过于复杂的正则表达式搜索- sounds 元素的 n-replace-copy-n-paste 操作感觉……有点脏。

我意识到在将整个内容输出到 JSON 文件之前,我可能已经放弃了这样做。任何我可以吸收的想法、技巧或解决方案示例将不胜感激!

没有 "json object" 这样的东西 - json 只是一种序列化/反序列化常见数据类型(字符串、数字、数组和关联数组)的方法。你的 Python 代码中只有 Python 个对象,在你的例子中是一个包含字典的列表(名为 JsonObject),它本身包含列表和字典,除了简单的基本知识之外,这里真的没有什么特别需要知道的Python 数据类型。

当然,您的 jsonObject 列表的列表方法中的 none 在这里会有任何用处,因为您要将文件列表存储到的对象是您刚刚附加到列表的字典,而不是列表本身。

解决方案很明显:只需将文件列表添加到您的元素之前(或当)将其附加到主列表时,即:

if files:
    elementId = basename(normpath(path)) + "Audio" 
    element = { 
      "elementId" : elementId, 
      "params" : { 
         "audioPath" : path, 
         "sounds" : list(files)
         },
      }
    jsonObject.append(element)

或更简单地说:

if files:
    elementId = basename(normpath(path)) + "Audio" 
    jsonObject.append({ 
      "elementId" : elementId, 
      "params" : { 
         "audioPath" : path, 
         "sounds" : list(files)
         },
      })