1

For example I have this json data which is read in from a file:

{"name": "Gilbert", "wins": [["straight", "7"], ["one pair", "10"]]}

How can I then display this in an edit text box with formatted indentations

{  
   "name":"Gilbert",
   "wins":[  
      [  
         "straight",
         "7"
      ],
      [  
         "one pair",
         "10"
      ]
   ]
}
Andy
  • 49,085
  • 60
  • 166
  • 233
JokerMartini
  • 5,674
  • 9
  • 83
  • 193

3 Answers3

3

use json library

import json

from PySide.QtGui import QApplication
from PySide.QtGui import QTextEdit

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)

    s = {"name": "Gilbert", "wins": [["straight", "7"], ["one pair", "10"]]}
    js = json.dumps(s, indent=4, sort_keys=True)
    w = QTextEdit()
    w.setText(js)
    w.show()
    sys.exit(app.exec_())

enter image description here

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
2

You can do this by using json.dumps() and putting the results into your text box.

A quick example (without pyside):

import json
s = """{"name": "Gilbert", "wins": [["straight", "7"], ["one pair", "10"]]}"""
print(json.dumps(j, indent=4, sort_keys=True))

Results:

{
    "name": "Gilbert",
    "wins": [
        [
            "straight",
            "7"
        ],
        [
            "one pair",
            "10"
        ]
    ]
}

If, instead of printing, the results of the json.dumps() you assign it to a variable:

p = json.dumps(j, indent=4, sort_keys=True)

You are now able to set the content of your text box to p using the QTextEdit's setText() slot

Andy
  • 49,085
  • 60
  • 166
  • 233
1

It's not the precise format you specify, but pprint.pformat with an appropriate width value produces a nicely-formatted string, which you can then insert into the text box:

import pprint
s = pprint.pformat({"name": "Gilbert", "wins": [["straight", "7"], ["one pair", "10"]]},
                   width=25)

Result:

>>> print(s)
{'name': 'Gilbert',
 'wins': [['straight',
           '7'],
          ['one pair',
           '10']]}
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97