-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e136366
commit 2f6f298
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import json | ||
|
||
# some JSON: | ||
x = '{ "name":"John", "age":30, "city":"New York"}' | ||
|
||
# parse x: | ||
y = json.loads(x) | ||
|
||
# the result is a Python dictionary: | ||
print(y["age"]) | ||
|
||
# Converting from a python object to json | ||
# a Python object (dict): | ||
x = {"name": "John", "age": 30, "city": "New York"} | ||
|
||
# convert into JSON: | ||
y = json.dumps(x) | ||
|
||
# the result is a JSON string: | ||
print(y) | ||
|
||
# Converting different types to json strings | ||
print(json.dumps({"name": "John", "age": 30})) | ||
print(json.dumps(["apple", "bananas"])) | ||
print(json.dumps(("apple", "bananas"))) | ||
print(json.dumps("hello")) | ||
print(json.dumps(42)) | ||
print(json.dumps(31.76)) | ||
print(json.dumps(True)) | ||
print(json.dumps(False)) | ||
print(json.dumps(None)) | ||
|
||
# Converting a python object containing all the legal data types | ||
x = { | ||
"name": "John", | ||
"age": 30, | ||
"married": True, | ||
"divorced": False, | ||
"children": ("Ann", "Billy"), | ||
"pets": None, | ||
"cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}], | ||
} | ||
|
||
print(json.dumps(x)) | ||
|
||
# Formatting the result | ||
print(json.dumps(x, indent=4)) | ||
|
||
# sort the result alphabetically by keys: | ||
print(json.dumps(x, indent=4, sort_keys=True)) |