แปลง multiple JSON object string ด้วย Python

สมมติว่าเรามี JSON object หลายๆ ตัวซ้อนกันอยู่ใน string แบบนี้ (multi line ด้วยอ่ะ ไม่งั้นล้นหน้า page wordpress)

json_string = = """
{"ID":1,"Key":{"Name":"A", "Surname":"A1"},"Pets":["Cat","Dog"]},
{"ID":9,"Key":{"Name":"Z", "Surname":"Z3"},"Pets":["Fish"]}
"""

ถ้าเรา convert มันให้กลายเป็น JSON object (จริงๆ คือ Python dict object) ด้วย json.loads(string) ตรงๆ ผลลัพท์ที่ได้จะบึ้มดังนี้

import json

json_string = = """
{"ID":1,"Key":{"Name":"A", "Surname":"A1"},"Pets":["Cat","Dog"]},
{"ID":9,"Key":{"Name":"Z", "Surname":"Z3"},"Pets":["Fish"]}
"""

json_obj = json.loads(json_string)

>>> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "...\lib\json\__init__.py", line 354, in load
s
    return _default_decoder.decode(s)
  File "...\lib\json\decoder.py", line 342, in decod
e
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 65 (char 64)

ทางแก้คือเราต้องทำให้ string ก้อนนั้นเป็น JSON array แล้วเราจะได้ array ของ JSON object มาวนแต่ละตัวได้

import json

json_string = """
[
    {"ID":1,"Key":{"Name":"A", "Surname":"A1"},"Pets":["Cat","Dog"]},
    {"ID":9,"Key":{"Name":"Z", "Surname":"Z3"},"Pets":["Fish"]}
]
"""

json_obj = json.loads(json_string)

print(json_obj[0])
>>> {'ID': 1, 'Key': {'Name': 'A', 'Surname': 'A1'}, 'Pets': ['Cat', 'Dog']}

print(json_obj2[1])
>>> {'ID': 9, 'Key': {'Name': 'Z', 'Surname': 'Z3'}, 'Pets': ['Fish']}

ป.ล. string ถ้าไม่ multi lines ก็ใช้วิธีเดียวกันนั่นแหละ

ป.ล. 2 เพิ่งเห็นว่าเจ้า Gutenberg editor นี่ช่องให้ code ไม่มีรองรับ code syntax, formatting โคตรกากกกกกก ห่วยกว่าเก่าอีก

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.