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"
      }
   ]
}
5
  • your input is a string ? Commented Apr 24, 2018 at 11:28
  • @toheedNiaz: its a list of objects called HeaderItem Commented Apr 24, 2018 at 11:30
  • What are HeaderItem objects? Where are they coming from? Commented Apr 24, 2018 at 11:30
  • Input is a ASCII file and everything is text. Commented Apr 24, 2018 at 11:33
  • @zwer: I have updated my question. Commented Apr 24, 2018 at 11:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent, exactly what i want.. thanks for the help.
I wanted to create single JSON file with different informations, like Version Information, how to add all the informations and write to file?
@Shankar - Instead of printing the data to STDOUT with json.dumps() use json.dump() to write it to a file. Check this answer as an example.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.