JSON คือไฟล์ JavaScript Object Notation ที่เก็บข้อมูลในรูปแบบ Dictionary ข้อมูลที่ JSON คืนค่าสามารถนำไปใช้ต่อได้ในภาษาอื่นๆ สำหรับวัตถุประสงค์ต่างๆ
Python มีไลบรารีอุดมสมบูรณ์สำหรับสร้างและพัฒนาแอปพลิเคชันจัดการข้อมูล JSON เราต้อง import json package จากไลบรารี Python
ในบทความนี้ เราจะสร้างฟังก์ชัน Python ที่คืนค่า JSON Object JSON เป็น Built-in library ที่มาพร้อมกับ Python แตถ้าต้องการติดตั้งแยก สามารถพิมพ์ "pip install json" ได้
สำหรับตัวอย่างนี้ เราจะสร้างฟังก์ชัน Python ที่มี Key-Value Pairs และสร้าง Dictionary จากนั้นส่งเข้าไปในเมธอด dump(dictionary) เป็นพารามิเตอร์ ซึ่งจะคืนค่า JSON Object
ตัวอย่าง
# Import JSON Library
import json
# Create and define the function
def fun():
title = "Python"
Tag = "Programming Language"
Category = "Open Source"
Downloads = "4500005230"
# Let us create the dictionary for the above data
dictionary = {
"title": title,
"Tag": Tag,
"Category": Category,
"Downloads": Downloads
}
return json.dumps(dictionary)
print(fun())
ผลลัพธ์
การรันโค้ดข้างต้นจะคืนค่า JSON Object จากฟังก์ชัน
{"title": "Python", "Tag": "Programming Language", "Category": "Open Source", "Downloads": "4500005230"}