English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
There is a requirement to display JSON formatted data in the standard output of Python, if the indentation is displayed, the data effect will be very good, here the use of the json package will have many operations
import json date = {u'versions': [{u'status': u'CURRENT', u'id': u'v2.3', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id': u'v2.2', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id': u'v2.1', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id': u'v2.0', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id': u'v1.1', u'links': [{u'href': u'http://controller:9292/v1/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id': u'v1.0', u'links': [{u'href': u'http://controller:9292/v1/', u'rel': u'self'}]}]} print json.dumps(data, sort_keys=True, indent=2) # Sort and indent two characters output
Otterrete l'output seguente:
"versions": [ "id": "v2.3" "links": [ "href": "http://controller:9292/v2/" "rel": "self" "status": "CURRENT" "id": "v2.2" "links": [ "href": "http://controller:9292/v2/" "rel": "self" "status": "SUPPORTED" "id": "v2.1" "links": [ "href": "http://controller:9292/v2/" "rel": "self" "status": "SUPPORTED" "id": "v2.0" "links": [ "href": "http://controller:9292/v2/" "rel": "self" "status": "SUPPORTED" "id": "v1.1" "links": [ "href": "http://controller:9292/v1/" "rel": "self" "status": "SUPPORTED" "id": "v1.0" "links": [ "href": "http://controller:9292/v1/" "rel": "self" "status": "SUPPORTED"
Si può vedere che tutto è stato formattato.
Questo è in Python, se si utilizza direttamente la riga di comando e si desidera convertire direttamente, è possibile usare data | python -mjson.tool per visualizzare i dati in formato JSON
echo '{"first_key": "value", "second_key": "value2"}' | python -mjson.tool
Ad esempio, se volete filtrare direttamente il valore di first_key dalla riga di comando, potete farlo così:
echo '{"first_key": "value", "second_key": "value2"}' | python -c 'import sys, json; print json.load(sys.stdin)[sys.argv[1]]' first_key
Otterrete il valore corretto.
Questo è tutto il contenuto del codice di esempio di output JSON in formato dati python che l'autore ha fornito, spero che riceviate molta supporto e applausi per il tutorial~