{"id":854,"date":"2017-11-16T13:50:18","date_gmt":"2017-11-16T18:50:18","guid":{"rendered":"http:\/\/bluegalaxy.info\/codewalk\/?p=854"},"modified":"2017-11-16T14:07:10","modified_gmt":"2017-11-16T19:07:10","slug":"python-how-to-read-and-write-json","status":"publish","type":"post","link":"https:\/\/bluegalaxy.info\/codewalk\/2017\/11\/16\/python-how-to-read-and-write-json\/","title":{"rendered":"Python: How to read and write JSON"},"content":{"rendered":"<p>JSON\u00a0is a lightweight data-interchange format that stands for <strong>J<\/strong>ava<strong>S<\/strong>cript <strong>O<\/strong>bject <strong>N<\/strong>otation. It so happens that JavaScript objects look exactly like Python dictionaries, so JSON objects can be thought of as portable dictionaries of key-value pairs. This portability is what makes JSON so valuable.<\/p>\n<p>While JSON objects can be identical to Python dictionaries, there are some caveats:<\/p>\n<p>JSON object keys and values must all be strings, and JavaScript uses double quotes to denote strings, so Python dictionaries that use single quotes for strings would be invalid JSON. If we want to convert a Python dictionary to a JSON object, then the single quotes would need to be converted to double quotes. In fact, this is exactly what the Python json module does when using the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">dumps()<\/code> function. The &#8216;s&#8217; stands for strings.<\/p>\n<p>For example, lets say we have a Python dictionary called fruit that looks like this:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">{'a':'apple', 'b':'banana', 'c':'cherry'}<\/pre>\n<p>When we convert this to a JSON object using <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">dumps()<\/code>, the string representation is changed to be more JavaScript friendly.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\"a\": \"apple\", \"c\": \"cherry\", \"b\": \"banana\"}<\/pre>\n<h4><strong>Python dictionary to JSON:<br \/>\n<\/strong><\/h4>\n<p>Here is the code that makes the conversion from Python dictionary to JSON. Notice it uses <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">dumps(python_dict)<\/code>. The argument is the Python dict to be converted:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import json\r\n\r\n# Python dict\r\nfruit =  {'a':'apple', 'b':'banana', 'c':'cherry'}  \r\n\r\n# Use the json module to convert the Python dict to a JSON object using .dumps()\r\nfruit_to_json = json.dumps(fruit)\r\n\r\nprint fruit_to_json<\/pre>\n<p>Just as Python dictionaries support multiple data types for values, JSON objects support key-value pairs where the values are either a list of strings or a sub-dictionary of key value pairs. For example, this is valid JSON:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n\t\"a\": {\"apple\": {\"type\": \"red delicious\"}},\r\n\t\"b\": \"banana\",\r\n\t\"c\": [\"cherry\", \"cantaloupe\"]\r\n}<\/pre>\n<p>Converting this Python dictionary to JSON and printing it out:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import json\r\n\r\n# Python dict\r\nfruit = {\r\n\t\"a\": {\"apple\": {\"type\": \"red delicious\"}},\r\n\t\"b\": \"banana\",\r\n\t\"c\": [\"cherry\", \"cantaloupe\"]\r\n}\r\n\r\n# Use the json module to convert the Python dict to a JSON object using .dumps()\r\nfj = json.dumps(fruit)\r\nprint fj\r\nprint type(fj)<\/pre>\n<p>Yields:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\"a\": {\"apple\": {\"type\": \"red delicious\"}}, \"c\": [\"cherry\", \"cantaloupe\"], \"b\": \"banana\"}\r\n&lt;type 'str'&gt;<\/pre>\n<p>Note: the\u00a0<code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">json.dumps()<\/code> function supports an argument called &#8216;indent&#8217; which will display the JSON object differently. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">fj = json.dumps(fruit, indent=4)\r\nprint fj<\/pre>\n<p>Which yields:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"json\">{\r\n    \"a\": {\r\n        \"apple\": {\r\n            \"type\": \"red delicious\"\r\n        }\r\n    }, \r\n    \"c\": [\r\n        \"cherry\", \r\n        \"cantaloupe\"\r\n    ], \r\n    \"b\": \"banana\"\r\n}<\/pre>\n<h4><strong>JSON to Python dictionary:<\/strong><\/h4>\n<p>Now that I&#8217;ve demonstrated how to convert a Python dictionary to a JSON object using the \u00a0<code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">json.dumps()<\/code> function, here is how we can do the reverse. To load a JSON object into a Python dictionary, we need to use the \u00a0<code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">json.loads()<\/code> function. (&#8216;s&#8217; stands for string). Remember that JSON objects are always transported as strings. For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import json\r\n\r\n# JSON object is transported as a string (dictionary with quotes around it)\r\njson_fruit = '{\"a\": {\"apple\": {\"type\": \"red delicious\"}}, \"c\": [\"cherry\", \"cantaloupe\"], \"b\": \"banana\"}'\r\n\r\nprint type(json_fruit)      # type is str\r\n\r\n# json.loads() converts the JSON string into a Python dict\r\npython_fruit = json.loads(json_fruit)\r\n\r\nprint type(python_fruit)    # type is dict<\/pre>\n<p>Which yields:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">&lt;type 'str'&gt;\r\n&lt;type 'dict'&gt;<\/pre>\n<p>In summary, JSON objects are transported as strings which can easily be converted to Python dictionaries using the \u00a0<code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">json.loads()<\/code> function. And Python dictionaries can be converted to JSON strings using the\u00a0 <code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">json.dumps()<\/code> function.<\/p>\n<p>Note: Sometimes you will need to load JSON from a file or a website instead of from a string. In those cases, use \u00a0<code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">json.load()<\/code> (without the &#8216;s&#8217;). For example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import json\r\njson_data = urllib2.urlopen('http:\/\/site.com\/data.json')\r\njson_obj = json.load(json_data)<\/pre>\n<p>For more information about the Python JSON module, see:<br \/>\n<a href=\"https:\/\/docs.python.org\/2\/library\/json.html\">https:\/\/docs.python.org\/2\/library\/json.html<\/a><\/p>\n<p>If you need to validate your JSON, there is an online tool called JSONlint:<br \/>\n<a href=\"https:\/\/jsonlint.com\/\">https:\/\/jsonlint.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>JSON\u00a0is a lightweight data-interchange format that stands for JavaScript Object Notation. It so happens that JavaScript objects look exactly like Python dictionaries, so JSON objects can be thought of as portable dictionaries of key-value pairs. This portability is what makes JSON so valuable. While JSON objects can be identical to Python dictionaries, there are some &hellip; <a href=\"https:\/\/bluegalaxy.info\/codewalk\/2017\/11\/16\/python-how-to-read-and-write-json\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Python: How to read and write JSON<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[45,62,4],"class_list":["post-854","post","type-post","status-publish","format-standard","hentry","category-python-language","tag-javascript","tag-json","tag-python"],"_links":{"self":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/854","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/comments?post=854"}],"version-history":[{"count":34,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/854\/revisions"}],"predecessor-version":[{"id":888,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/854\/revisions\/888"}],"wp:attachment":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/media?parent=854"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/categories?post=854"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/tags?post=854"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}