English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example code of outputting data in JSON format in Python

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, and many operations will be involved in using the json package here

import json
date = {\"versions\": [{\"status\": \"CURRENT\", \"id\": \"v\"}]}2.3//controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id2.2//controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id2.1//controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id2.0', u'links': [{u'href': u'http://controller:9292/v2/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id1.1//controller:9292/v1/', u'rel': u'self'}]}, {u'status': u'SUPPORTED', u'id1.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

 This will produce the following output:

{
 "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"
  }
 ]
}

You can see that it has been formatted.

This is in Python, if you use the command line directly, and want to convert directly, you can use data | python -mjson.tool to output JSON formatted data

echo '{"first_key": "value", "second_key": "value2"}' | python -mjson.tool

For example, if you want to filter and get the value of 'first_key' directly in the command line, you can do it like this:

echo '{"first_key": "value", "second_key": "value2"}' | python -c 'import sys, json; print json.load(sys.stdin)[sys.argv[1]' first_key

Then you will get the corresponding value.

This is the full content of the example code that the editor has brought to you for Python to output data in JSON format, I hope everyone will support and cheer for the tutorial~

You May Also Like