Python json: Difference between revisions

From wikinotes
 
No edit summary
 
Line 1: Line 1:
 
= Documentation =
{{
<blockquote>
TODO |  
{| class="wikitable"
use and document the usageof simplejson
|-
}}
| 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">
my_dict = {
with open(filepath, 'w') as fd:
'a': 1,
    fd.write(json.dumps({'a': 1}, indent=4))
'b': 2,
}
 
with open( filepath, 'w' ) as fw:
fw.write( json.dumps(my_dict, indent=2) )
 
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- write -->
</blockquote><!-- write -->


Line 44: Line 40:
<blockquote>
<blockquote>
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
with open( filepath, 'r' ) as stream:
with open(filepath, 'r') as fd:
my_dict = json.load(stream)
    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)