convert list of objects to Json array

Shankar

I'm new to python and i have a list of objects like this.

Sample code

>>> for val in las.version:
...     print(val.mnemonic)
...     print(val.unit)
...     print(val.value)
...     print(val.descr)
...
VERS

1.2
some description
WRAP

NO
another description
>>>

I wanted to convert this as JSON array.

{  
   "versionInformation":[  
      {  
         "mnemonic":"VERS",
         "unit":"",
         "value":"2.0",
         "description":"some description"
      },
      {  
         "mnemonic":"WRAP",
         "unit":"",
         "value":"NO",
         "description":"another description"
      }
   ]
}
zwer

Without the HeaderItem description this cannot account for possible errors, but you can easily recreate the JSON structure using dict/list combos and then use the built-in json module to get your desired JSON, i.e.:

import json

version_info = [{"mnemonic": v.mnemonic, "unit": v.unit,
                 "value": v.value, "description": v.descr}
                for v in las.version]
print(json.dumps({"versionInformation": version_info}, indent=3))

Keep in mind that prior to CPython 3.6 and Python 3.7 in general, the order of the items in the JSON of individual version info cannot be guaranteed. You can use collections.OrderedDict instead if that's important - it shouldn't be, tho, given that JSON by specification uses unordered mappings.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related