I can't figure out how to select a specific element in a JSON object, and I cant come up with a search phrase to google.
Nội dung chính Show
Ví dụ về ghi dữ liệu JSON trong Python Ví dụ về Import JSON, khai báo, đọc và in dữ liệu JSON bằng Python Ví dụ về ghi dữ liệu JSON trong Python Để ghi dữ liệu JSON ra file trong Python, ta sử dụng method import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
1. print(mylist['durian']) This is my JSON
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
how can I select the URL where the key is MOBILE?
thanks!
asked Jul 17, 2015 at 19:49Jul 17, 2015 at 19:49
NCSNCSNCS
1832 gold badges3 silver badges12 bronze badges 2 gold
badges 3 silver badges 12 bronze badges
4
First, convert your JSON document into a python object using json.loads
or json.load
Second, loop through the "urls" dictionary looking for the item in question For example:
import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
answered Jul 17, 2015 at 20:00Jul 17, 2015 at 20:00
RobᵩRobᵩRobᵩ
157k17 gold badges226 silver badges301 bronze badges 17 gold badges 226 silver badges 301 bronze badges
Something like this I believe should do the trick.
first = {"a": 1, "b": 2, "c": 3,, "d": 4, "e": }
second = {"b": 3, "c": 4, "d": 5, "e": 6, "f": 7}
values = {"a","b","c"}
first.update((key, val) for (key, val) in second.items() if key in values)
answered Jul 17, 2015 at 19:58Jul 17, 2015 at 19:58
MaddyMaddyMaddy
1,9804 gold badges24 silver badges57 bronze badges 4 gold badges 24 silver badges 57 bronze badges
Ví dụ về ghi dữ liệu JSON trong Python
JSON (JavaScript Object Notation): Là một định dạng dữ liệu rất phổ biến, được dùng để lưu trữ và thể hiện các dữ liệu có cấu trúc. (J avaScript O bject N otation): Là một định dạng dữ liệu rất phổ biến, được dùng để lưu trữ và thể hiện các dữ liệu có cấu trúc.
JSON là định dạng dữ liệu phổ biến được sử dụng để truyền và nhận dữ liệu giữa ứng dụng web và web server.
Python cho phép thao tác với JSON dưới dạng chuỗi hoặc lưu đối tượng JSON vào trong file.JSON dưới dạng chuỗi hoặc lưu đối tượng JSON vào
trong file.
Hướng dẫn Lập trình với JSON trong Python
Ví dụ về Import JSON, khai báo, đọc và in dữ liệu JSON bằng Python
Để có thể làm việc với JSON, ta cần import module json. Ta cần import module trước khi gọi các hàm để thao tác với json. làm việc với JSON, ta cần import module
json . Ta cần import module trước khi gọi các hàm để thao tác với json.
Để có thể parse một JSON string, ta gọi method json.loads()
. Phương thức này sẽ trả về một đối tượng dictionary chứa dữ liệu được chứa trong JSON string.parse một JSON string , ta gọi method json.loads()
. Phương thức này sẽ trả về một đối tượng dictionary chứa dữ liệu được chứa trong JSON string.
Ví dụ:
Trong ví dụ này, ta đã khai báo một string có chứa dữ liệu JSON, rồi gọi method loads()
để xử lý chuỗi này.
Phương thức loads()
sẽ trả về một đối tượng dictionary chứa toàn bộ dữ liệu json.
Sau đó ta in ra toàn bộ dữ liệu trong dictionary, rồi in ra value của key là ‘durian’
.
import json json
# Khai báo một JSON string
listfruits = '{"orange":"Qua cam", "strawberry":"Day tay", '\ = '{"orange":"Qua cam", "strawberry":"Day tay", ' \
'"grape":"Nho", "durian":"Sau rieng"}'
# Đọc JSON String, method này trả về một Dictionary
mylist = json.loads(listfruits) = json .loads (listfruits )
# In ra thông tin của Dictionary
print(mylist) (mylist )
# In ra một giá trị trong Dictionary
print(mylist['durian']) (mylist ['durian' ])
Kết quả được hiển thị như trong hình bên dưới:
Khởi tạo dữ liệu JSON trong Python
Ví dụ về ghi dữ liệu JSON trong Python
Để đọc một file có chứa JSON object, ta gọi method json.load()
.
Để chuyển đổi từ một dictionary thành một JSON string, ta gọi method
import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
0. Để ghi dữ liệu JSON ra file trong Python, ta sử dụng method
import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
1. Ví dụ:
Trong ví dụ này, ta đã khai báo một string có chứa dữ liệu JSON, rồi gọi method loads()
để xử lý chuỗi này.khai báo một chuỗi chứa dữ liệu JSON .
Phương thức loads()
sẽ trả về một đối tượng dictionary chứa toàn bộ dữ liệu json.tạo và mở file có tên là
import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
2. Sau đó ta gọi phương thức import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
3 để ghi dữ liệu json vào file.
Sau đó ta in ra toàn bộ dữ liệu trong dictionary, rồi in ra value của key là ‘durian’
.
coffees = "{"capuchino":"Cafe Italian", = "{" capuchino":" Cafe Italian",
"expresso": ["Matcha", "Mocha"], : ["Matcha" , "Mocha" ],
"VietNam": True, : True ,
"latte": 32 : 32
# Khai báo một JSON string"
listfruits = '{"orange":"Qua cam", "strawberry":"Day tay", '\
with open('coffee.txt', 'w') as myfile: open ('coffee.txt' , 'w' ) as myfile :
# Đọc JSON String, method này trả về một Dictionary .dump (coffees , myfile )
# In ra thông tin của Dictionary ('Ghi file thanh cong !' )
# In ra một giá trị trong Dictionary
print(mylist['durian'])
Kết quả được hiển thị như trong hình bên dưới:
Khởi tạo dữ liệu JSON trong Python
Ví dụ về ghi dữ liệu JSON trong Python
Để đọc một file có chứa JSON object, ta gọi method json.load()
.
Để chuyển đổi từ một dictionary thành một JSON string, ta gọi method import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
0.
Trong ví dụ này, ta đã khai báo một chuỗi chứa dữ liệu JSON. cung cấp các tham số để cho phép định dạng kết quả (thụt lề) hoặc sắp xếp kết quả xử lý.
Ví dụ:
Tiếp theo ta tạo và mở file có tên là
import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
2. Sau đó ta gọi phương thức import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
3 để ghi dữ liệu json vào file.khai báo một string json gồm các loại trái cây.# Khai báo JSON Stringgọi method import json
json_document='''
{
"originalRequest": {
"category": {}
},
"totalResultSize": 209,
"products": [
{
"id": "1000004006560322",
"ean": "0828768235928",
"gpc": "music",
"title": "title",
"specsTag": "tag",
"summary": "summary",
"rating": 45,
"urls": [
{
"key": "DESKTOP",
"value": "http://www.url.com"
},
{
"key": "MOBILE",
"value": "https://m.url.com"
}
]
}
]
}
'''
python_obj = json.loads(json_document)
for url in python_obj["products"][0]["urls"]:
if url["key"] == "MOBILE":
value = url["value"]
break
else:
# Some default action
print "No url found"
value = "http://www.url.com"
print "Value:", value
5 để xử lý string json ở trên.
}"truyền 2 tham số cho method này, để cho phép thụt lề kết quả vào 4 ký tự, và sắp xếp kết quả theo thứ tự aphabet của key.
Sau đó ta in ra toàn bộ dữ liệu trong dictionary, rồi in ra value của key là ‘durian’
.
danhsachhoaqua = "{ = "{
# Khai báo một JSON string :"Qua xoai" ,
"strawberry":"Dau tay", :"Dau tay" ,
"avocado":"Qua bo", :"Qua bo" ,
"durian":"Sau rieng", :"Sau rieng" ,
"orange":"Qua cam", :"Qua cam" ,
"lemon":"Dua hau", :"Dua hau" ,
"coconut":"Qua dua", :"Qua dua" ,
# Khai báo một JSON string"
listfruits = '{"orange":"Qua cam", "strawberry":"Day tay", '\
# Đọc JSON String, method này trả về một Dictionary (json .dump (danhsachhoaqua , indent =4 , sort_keys =True ))
# In ra thông tin của Dictionary
# In ra một giá trị trong Dictionary
print(mylist['durian'])
Kết quả được hiển thị như trong hình bên dưới:KHÓA HỌC PYTHON để có kiến thức đầy đủ, bài bản hơn.
Khởi tạo dữ liệu JSON trong Python