Python json: Difference between revisions
From wikinotes
(→write) |
No edit summary |
||
Line 1: | Line 1: | ||
= Documentation = | |||
{ | <blockquote> | ||
{| class="wikitable" | |||
|- | |||
} | | official docs || https://docs.python.org/3/library/json.html?highlight=json#module-json | ||
|- | |||
|} | |||
</blockquote><!-- Documentation --> | |||
= datatypes = | = datatypes = | ||
Line 16: | Line 19: | ||
"boolean" = true, | "boolean" = true, | ||
"null" = null | "null" = null | ||
} | } | ||
// compound datatypes | // compound datatypes | ||
Line 29: | Line 32: | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
with open(filepath, 'w') as fd: | |||
fd.write(json.dumps({'a': 1}, indent=4)) | |||
with open( filepath, 'w' ) as | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- write --> | </blockquote><!-- write --> | ||
Line 44: | Line 40: | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
with open( filepath, 'r' ) as | with open(filepath, 'r') as fd: | ||
my_dict = json.load(fd) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- read --> | </blockquote><!-- read --> |
Latest revision as of 21:42, 19 September 2021
Documentation
official docs https://docs.python.org/3/library/json.html?highlight=json#module-json
datatypes
JSON natively supports 6x datatypes:
// simple datatypes { "string" = "my string", "number" = 9999, "boolean" = true, "null" = null } // compound datatypes { "object" = { "a":1, "b":1 }, // a dictionary "array" = [ "a","b","c" ] }
write
with open(filepath, 'w') as fd: fd.write(json.dumps({'a': 1}, indent=4))
read
with open(filepath, 'r') as fd: my_dict = json.load(fd)