自定义Python JSON object_hook

时间:2018-11-15 19:06:50

标签: python json python-3.x

我正在尝试在Python 3中使用object_hook自定义json数据,但不知道如何开始。非常感谢任何指针。我正在尝试引入一个新密钥,并将现有数据移动到Python Object中的新密钥中。

我正在尝试在json文本下面转换:

{
  "output": [
    {
      "Id": "101",
      "purpose": "xyz text",
      "array": [
        {
          "data": "abcd"
        },
        {
          "data": "ef gh ij"
        }
      ]
    },
    {
      "Id": "102",
      "purpose": "11xyz text",
      "array": [
        {
          "data": "abcd"
        },
        {
          "data": "java"
        },
        {
          "data": "ef gh ij"
        }
      ]
    }
  ]
}

{
  "output": [
    {
      "Id": "101",
      "mydata": {
        "purpose": "xyz text",
        "array": [
          {
            "data": "abcd"
          },
          {
            "data": "ef gh ij"
          }
        ]
      }
    },
    {
      "Id": "102",
      "mydata": {
        "purpose": "11xyz text",
        "array": [
          {
            "data": "abcd"
          },
          {
            "data": "java"
          },
          {
            "data": "ef gh ij"
          }
        ]
      }
    }
  ]
}

我的Python JSON对象挂钩定义为:

class JSONObject:
    def __init__( self, dict ):
        vars(self).update( dict )

    def toJSON(self):
        return json.dumps(self, default=lambda o: o.__dict__, 
            sort_keys=True, indent=4)

1 个答案:

答案 0 :(得分:0)

您可以指定自定义object_pairs_hookinput_json是输入JSON的字符串)。

def mydata_hook(obj):
    obj_d = dict(obj)
    if 'Id' in obj_d:
        return {'Id': obj_d['Id'], 'mydata': {k: v for k, v in obj_d.items() if 'Id' not in k}}
    else:
        return obj_d

print(json.dumps(json.loads(input_json, object_pairs_hook=mydata_hook), indent=2))

输出:

{
  "output": [
    {
      "mydata": {
        "array": [
          {
            "data": "abcd"
          }, 
          {
            "data": "ef gh ij"
          }
        ], 
        "purpose": "xyz text"
      }, 
      "Id": "101"
    }, 
    {
      "mydata": {
        "array": [
          {
            "data": "abcd"
          }, 
          {
            "data": "java"
          }, 
          {
            "data": "ef gh ij"
          }
        ], 
        "purpose": "11xyz text"
      }, 
      "Id": "102"
    }
  ]
}