2

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"
      }
   ]
}
Shankar
  • 8,529
  • 26
  • 90
  • 159

2 Answers2

6

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.

zwer
  • 24,943
  • 3
  • 48
  • 66
  • Excellent, exactly what i want.. thanks for the help. – Shankar Apr 24 '18 at 11:48
  • I wanted to create single JSON file with different informations, like Version Information, how to add all the informations and write to file? – Shankar Apr 24 '18 at 12:16
  • 1
    @Shankar - Instead of printing the data to STDOUT with `json.dumps()` use `json.dump()` to write it to a file. Check [**this answer**](https://stackoverflow.com/a/12309296/7553525) as an example. – zwer Apr 24 '18 at 12:19
3
from pprint import pprint


result = {}
result['versionInformation'] = []

for val in las.version:
    version_info = {}
    version_info['mnemonic'] = val.mnemonic
    version_info['unit'] = val.unit
    version_info['value'] = val.value
    version_info['description'] = val.descr

    result['versionInformation'].append(version_info)


pprint(result)
Yassine Faris
  • 951
  • 6
  • 26