繁体   English   中英

Python Json 来自 Ordered Dict

[英]Python Json from Ordered Dict

我正在尝试创建一个嵌套的 Json 结构,如下所示:

示例 Json:

      {
        "id" : "de",
        "Key" : "1234567",
        "from" : "test@test.com",
        "expires" : "2018-04-25 18:45:48.3166159",
        "command" : "method.exec",
        "params" : {
          "method" : "cmd",
          "Key" : "default",
          "params" : {
            "command" : "testing 23"
          }
        }

我正在尝试从 OrderedDict 执行此操作。 我不确定构建 OrderedDict 的正确方法,以便生成正确的 Json。

Python 代码:

json_payload = OrderedDict(
                            [('id', id),
                                ('Key', keystore),
                                ('from', 'test@test.com'),
                                ('expires', expires),
                                ('command', 'method.exec')]

                              # What goes here for the params section??
                           )
print json.dumps(json_payload, indent=4, default=str)

您在JSON数据的末尾错过了}

import json
import collections

data =  {
        "id" : "de",
        "Key" : "1234567",
        "from" : "test@test.com",
        "expires" : "2018-04-25 18:45:48.3166159",
        "command" : "method.exec",
        "params" : {
          "method" : "cmd",
          "Key" : "default",
          "params" : {
            "command" : "testing 23"
          }
        }}

data_str = json.dumps(data)
result = json.loads(data_str, object_pairs_hook=collections.OrderedDict)
print(result)

输出:

OrderedDict(
  [
    ('id', 'de'), 
    ('Key', '1234567'), 
    ('from', 'test@test.com'), 
    ('expires', '2018-04-25 18:45:48.3166159'), 
    ('command', 'method.exec'), 
    ('params', 
      OrderedDict(
        [
          ('method', 'cmd'), 
          ('Key', 'default'),
          ('params', 
            OrderedDict(
              [
               ('command', 'testing 23')
              ]
            )
          )
        ]
      )
    )
  ]
)

一些东西。 id是一个关键字。 您可以仅将字典作为参数传递。

ids = "de"
keystore = "1234567"
expires = "2018-04-25 18:45:48.3166159"
pdict = {
          "method" : "cmd",
          "Key" : "default",
          "params" : {
            "command" : "testing 23"
                     }
         }
json_payload = OrderedDict(
                            [('id', id),
                                ('Key', keystore),
                                ('from', 'test@test.com'),
                                ('expires', expires),
                                ('command', 'method.exec'),
                                ('params',pdict )
                            ]
                           )
print(json.dumps(json_payload, indent=4, default=str))

使用@haifzhan的输出作为输入,可以准确地交付所需的内容。

 payload = OrderedDict(
      [
        ('id', 'de'), 
        ('Key', '1234567'), 
        ('from', 'test@test.com'), 
        ('expires', '2018-04-25 18:45:48.3166159'), 
        ('command', 'method.exec'), 
        ('params', 
          OrderedDict(
            [
              ('method', 'cmd'), 
              ('Key', 'default'),
              ('params', 
                OrderedDict(
                  [
                   ('command', 'testing 23')
                  ]
                )
              )
            ]
          )
        )
      ]
    )
print json.dumps(json_payload, indent=4, default=str)

在职的 !!!
大多数情况下,当我们序列化查询集而不是 model 实例时,例如:

serialized_data = SnippetSerializer(MyModel.objects.all(), many=True)

Output:

[
OrderedDict([('code', 'ABC'),  ('quantity', 5.0)]),
OrderedDict([('code', 'GGG'), ('quantity', 4.0)])
]

我们可以像这样将其转换为 json:-

from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
import io
result = JSONRenderer().render(serialized_data)
output_stream = io.BytesIO(result)
data = JSONParser().parse(output_stream)
print(data)

Output:

 [
    {'code': 'ABC', 'quantity': 5.0}, 
    {'code': 'GGG', 'quantity': 4.0}
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM