ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Python/Module] JSON
    코딩/Python 2022. 12. 22. 13:58
    728x90

    JSON

    • syntax for storing and exchanging data
    • text, JavaScript object notation
    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"])

    Parse JSON - Convert from JSON to Python: json.loads()

    • result: dictionary

    Convert from Python to JSON: json.dumps()

    import json
    
    # a Python object (dict):
    x = {
      "name": "John",
      "age": 30,
      "city": "New York"
    }
    
    # convert into JSON:
    y = json.dumps(x)

    convert Python objects into JSON strings:

    • dict
    • list
    • tuple
    • string
    • int
    • float
    • True
    • False
    • None
    import json
    
    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))

    Python objects vs. JSON (JavaScript)

    Python JSON
    dict Object
    list Array
    tuple Array
    str String
    int Number
    float Number
    TRUE TRUE
    FALSE FALSE
    None null

    Format the Result

    • indent
    • seperator
    • sort key
    json.dumps(x, indent=4, separators=(". ", " = "), sort_keys=True)
    728x90

    '코딩 > Python' 카테고리의 다른 글

    [Python] Tree demo  (0) 2022.12.22
    [Python/Module] RegEx  (1) 2022.12.22
    [Python tutorial] 28. Reference  (0) 2022.12.21
    [Python tutorial] 27. Exception  (0) 2022.12.21
    [Python/Module] Datetime  (1) 2022.12.21

    댓글

Designed by Tistory.