Python Json из заказанного Dict - PullRequest
0 голосов
/ 26 апреля 2018

Я пытаюсь создать вложенную структуру 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)

Ответы [ 3 ]

0 голосов
/ 26 апреля 2018

Вы пропустили } в конце ваших данных 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')
              ]
            )
          )
        ]
      )
    )
  ]
)
0 голосов
/ 26 апреля 2018

Использование вывода @ 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)
0 голосов
/ 26 апреля 2018

Несколько вещей. 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))
...