{"id":243,"date":"2023-12-31T11:20:51","date_gmt":"2023-12-31T17:20:51","guid":{"rendered":"https:\/\/www.baizhao666.com\/?p=243"},"modified":"2024-07-17T18:43:54","modified_gmt":"2024-07-18T00:43:54","slug":"json-files","status":"publish","type":"post","link":"https:\/\/www.baizhao666.com\/?p=243","title":{"rendered":"JSON files"},"content":{"rendered":"\n<p>In computer science, JSON stands for JavaScript Object Notation. JSON files are what XML files were originally supposed to be. They are often thought of as an &#8220;imporvement&#8221; on XML files.<\/p>\n\n\n\n<!--more-->\n\n\n\n<h3 class=\"wp-block-heading\">Difference between JSON and XML<\/h3>\n\n\n\n<p>An XML file looks like this:<\/p>\n\n\n\n<pre class=\"wp-block-code language-xml\"><code>&lt;employees&gt;\n  &lt;employee&gt;\n    &lt;firstName&gt;John&lt;\/firstName&gt; &lt;lastName&gt;Doe&lt;\/lastName&gt;\n  &lt;\/employee&gt;\n  &lt;employee&gt;\n    &lt;firstName&gt;Anna&lt;\/firstName&gt; &lt;lastName&gt;Smith&lt;\/lastName&gt;\n  &lt;\/employee&gt;\n  &lt;employee&gt;\n    &lt;firstName&gt;Peter&lt;\/firstName&gt; &lt;lastName&gt;Jones&lt;\/lastName&gt;\n  &lt;\/employee&gt;\n&lt;\/employees&gt;<\/code><\/pre>\n\n\n\n<p>Notice that in a XML file, the data was covered by some tags. which make the file too long and hard to read. By contrast, a JSON file look like this:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-json\" data-lang=\"JSON\"><code>{&quot;employees&quot;:[\n    {&quot;firstName&quot;:&quot;John&quot;, &quot;lastName&quot;:&quot;Smith&quot;},\n    {&quot;firstName&quot;:&quot;Anna&quot;, &quot;lastName&quot;:&quot;Doe&quot;},\n    {&quot;firstName&quot;:&quot;Peter&quot;, &quot;lastName&quot;:&quot;Jones&quot;}\n]}<\/code><\/pre><\/div>\n\n\n\n<p>In a JSON file, the data was stored as key:value pairs. It&#8217;s similar to the format of dictionaies in Python. What&#8217;s more, there is a thematic connection with OOP: it&#8217;s almost like there is a class called &#8220;employees&#8221; and we have three objects of that class, and each have two attributes: firstName and lastName.<\/p>\n\n\n\n<p>JSON files have some advantages over XML file. They tend to be shorter and easier to type (because of the lack of &#8220;closing tags&#8221;). They are automatically compatible with JavaScript, which all computers and web browsers use, and in general are a little easier to run than XML files. They are also in some cases faster to run than XML files. Also, JSON is better for arrays.<\/p>\n\n\n\n<p>A general template for JSON files is:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-json\" data-lang=\"JSON\"><code>{\n    &quot;array (or python list)&quot;: [\n        1,\n        2,\n        3...\n    ],\n    &quot;boolean&quot;: true,\n    &quot;color&quot;: &quot;gold&quot;,\n    &quot;null (None in python)&quot;: null,\n    &quot;number&quot;: 123,\n    &quot;object (or python dictionary)&quot;: {\n        &quot;a&quot;: &quot;b&quot;,\n        &quot;c&quot;: &quot;d&quot;\n    },\n    &quot;string&quot;: &quot;hello world&quot;\n}<\/code><\/pre><\/div>\n\n\n\n<p>To work with JSON format:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>JavaScript Onject Notation<\/li>\n\n\n\n<li>It&#8217;s a plain text format<\/li>\n\n\n\n<li>Ideal in situtations when we don&#8217;t know who will be using our data and what language they might be using (language independent)<\/li>\n\n\n\n<li>JSON files can be opened\/edited with any text editor<\/li>\n\n\n\n<li>Basic foramt of a JSON object is {&#8220;key&#8221;: value}, just like a dictionary in python<\/li>\n\n\n\n<li>Key MUST always be a string with quotation marks (&#8220;&#8221;)<\/li>\n\n\n\n<li>Value can be anything: strings, numbers(int or float), boolean, arrays, other JSON objects, and null (which is None in python)<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Create\/read JSON file<\/h3>\n\n\n\n<p>There is actually a module in python called &#8220;json&#8221; that allows us to interact with JSON files. In python, to create a basic json file, all we need is a dictionary that we can &#8220;dump&#8221; into the created file.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># write into a JSON file\nimport json\n\nmy_dict = {&quot;one&quot;: 1, &quot;two&quot;: 2, &quot;three&quot;: 3}\nwith open(&quot;my_json.json&quot;, &quot;w&quot;) as f:\n    json.dump(my_dict, f, indent=2)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">{\n  \"one\": 1,\n  \"two\": 2,\n  \"three\": 3\n}<\/pre>\n\n\n\n<p>Notice that the JSON file that we made is end with &#8220;.json&#8221;. In order to write the content of the dictionary into a json file, we need to open this file first using &#8220;with open()&#8221; in write mode. Within the dump() function, the first argument is the dictionary that we want to &#8220;dump&#8221;, the second argument is the file stream, and the &#8220;indent&#8221; argument is used to indent the JSON file to make it easy to read.<\/p>\n\n\n\n<p>To open and read from a JSON file, we can do it in a similar way. But the JSON file needs to exist otherwise an error will be raised.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code># read from a JSON file\nimport json\n\nwith open(&quot;my_json.json&quot;, &quot;r&quot;) as f:\n    file_content = json.load(f)\n    print(file_content)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">{'one': 1, 'two': 2, 'three': 3}<\/pre>\n\n\n\n<p>Notice that the content read from a JSON file will be stored in a dictionary, we can access the content by the keys.<\/p>\n\n\n\n<p>From Mozilla: Converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization.<\/p>\n\n\n\n<p>Addition notes on dump() and load():<\/p>\n\n\n\n<p>The dump() function will write a dictionary into a JSON file, and the load() function will read from a JSON file and store it into a dictionary. While the dumps() function will serialize a dictionary to a JSON formatted string, and the loads() function will turn a JSON formatted string into a dictionary.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Object-oriented programming and JSON file<\/h3>\n\n\n\n<p>As the thematic connection with OOP, objects can be encoded and saved in a JSON file. As an instance, we can make a large JSON file that contains a bunch of car object data.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>import json\n\nclass Car:\n    def __init__(self, color, year, make, model):\n        self.color = color\n        self.year = year\n        self.make = make\n        self.model = model\n\nD = {}\nfor i in range(30):\n    year = 1990 + i\n    D[year] = vars(Car(&quot;red&quot;, year, &quot;Civic&quot;, &quot;Honda&quot;))\n\nwith open(&quot;car.json&quot;, &quot;w&quot;) as f:\n    json.dump(D, f, indent=2)<\/code><\/pre><\/div>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">{\n  \"1990\": {\n    \"color\": \"red\",\n    \"year\": 1990,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1991\": {\n    \"color\": \"red\",\n    \"year\": 1991,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1992\": {\n    \"color\": \"red\",\n    \"year\": 1992,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1993\": {\n    \"color\": \"red\",\n    \"year\": 1993,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1994\": {\n    \"color\": \"red\",\n    \"year\": 1994,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1995\": {\n    \"color\": \"red\",\n    \"year\": 1995,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1996\": {\n    \"color\": \"red\",\n    \"year\": 1996,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1997\": {\n    \"color\": \"red\",\n    \"year\": 1997,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1998\": {\n    \"color\": \"red\",\n    \"year\": 1998,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"1999\": {\n    \"color\": \"red\",\n    \"year\": 1999,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2000\": {\n    \"color\": \"red\",\n    \"year\": 2000,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2001\": {\n    \"color\": \"red\",\n    \"year\": 2001,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2002\": {\n    \"color\": \"red\",\n    \"year\": 2002,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2003\": {\n    \"color\": \"red\",\n    \"year\": 2003,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2004\": {\n    \"color\": \"red\",\n    \"year\": 2004,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2005\": {\n    \"color\": \"red\",\n    \"year\": 2005,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2006\": {\n    \"color\": \"red\",\n    \"year\": 2006,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2007\": {\n    \"color\": \"red\",\n    \"year\": 2007,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2008\": {\n    \"color\": \"red\",\n    \"year\": 2008,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2009\": {\n    \"color\": \"red\",\n    \"year\": 2009,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2010\": {\n    \"color\": \"red\",\n    \"year\": 2010,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2011\": {\n    \"color\": \"red\",\n    \"year\": 2011,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2012\": {\n    \"color\": \"red\",\n    \"year\": 2012,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2013\": {\n    \"color\": \"red\",\n    \"year\": 2013,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2014\": {\n    \"color\": \"red\",\n    \"year\": 2014,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2015\": {\n    \"color\": \"red\",\n    \"year\": 2015,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2016\": {\n    \"color\": \"red\",\n    \"year\": 2016,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2017\": {\n    \"color\": \"red\",\n    \"year\": 2017,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2018\": {\n    \"color\": \"red\",\n    \"year\": 2018,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  },\n  \"2019\": {\n    \"color\": \"red\",\n    \"year\": 2019,\n    \"make\": \"Civic\",\n    \"model\": \"Honda\"\n  }\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In computer science, JSON stands for JavaScript Object Notation. JSON files are what XML files were originally supposed to be. They are often thought of as an &#8220;imporvement&#8221; on XML files.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[],"class_list":["post-243","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/243","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=243"}],"version-history":[{"count":4,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/243\/revisions"}],"predecessor-version":[{"id":269,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=\/wp\/v2\/posts\/243\/revisions\/269"}],"wp:attachment":[{"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=243"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=243"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.baizhao666.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=243"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}