简体   繁体   English

Python Json 来自 Ordered Dict

[英]Python Json from Ordered Dict

I am tryinging to create a nested Json structure as follows:我正在尝试创建一个嵌套的 Json 结构,如下所示:

Example 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"
          }
        }

I am trying to do this from an OrderedDict.我正在尝试从 OrderedDict 执行此操作。 I am not sure of the correct way to structure the OrderedDict so that the correct Json is produced.我不确定构建 OrderedDict 的正确方法,以便生成正确的 Json。

Python Code: 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)

You missed a } at the end of your JSON data. 您在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)

Output: 输出:

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')
              ]
            )
          )
        ]
      )
    )
  ]
)

A few things. 一些东西。 id is a keyword. id是一个关键字。 You can just pass a dictionary as a parameter. 您可以仅将字典作为参数传递。

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))

Using @haifzhan's output as the input delivered exactly what was required. 使用@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)

WORKING !!!在职的 !!!
Mostly When We serialize querysets instead of model instances Ex:大多数情况下,当我们序列化查询集而不是 model 实例时,例如:

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

Output: Output:

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

We can convert it to json like this: -我们可以像这样将其转换为 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: 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