简体   繁体   中英

Python Json from Ordered Dict

I am tryinging to create a nested Json structure as follows:

Example 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. I am not sure of the correct way to structure the OrderedDict so that the correct Json is produced.

Python Code:

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.

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

 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:

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

Output:

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

We can convert it to json like this: -

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}
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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