生成一个只包含 json 文件的结构部分(即括号)而没有其他内容的文件

Generate a file that only contains the structural parts (i.e. brackets) of a json file without other contents

有没有办法使用 Python 提取 json 文件的结构细节?

我有一个看起来像这样的文件:

{
"help": "https://?name=package_search", 
"success": true,
"result": {
      "count": 47, 
      "facets": {}, 
      "results": [
         {
           "author": "ggm",
           "author_email": "ggm@____.nl",
           "creator_user_id": "x_x_x_x" }]}}

而我只想看到这样的结构:

{
   {
      [
       {
        }
       {
        }
         ]
              }
                   }

这可以用 Python 实现吗?

您可以使用正则表达式(假设数据仍为字符串形式且尚未解析为字典):

import re

s = """{
"help": "https://?name=package_search", 
"success": true,
"result": {
      "count": 47, 
      "facets": {}, 
      "results": [
         {
           "author": "ggm",
           "author_email": "ggm@____.nl",
           "creator_user_id": "x_x_x_x" }]}}"""

print(re.sub(r"[^{}[\]\n]", ' ', s))

将给予:

{
                                        
                
          {
                   
                {}  
                 [
         {
                           
                                         
                                        }]}}

这使用 re.sub which is the regex version of replace and basically says: "Replace everything except brackets and new line with a space" (see the demo).