问题描述:

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"

]

]

}

网友答案:

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_())

网友答案:

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

网友答案:

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']]}
相关阅读:
Top