在Python中联接并格式化对象数组 [英] Join and format array of objects in Python
本文介绍了在Python中联接并格式化对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将值和对象数组连接并格式化为python中的字符串.我有什么办法吗?
I want to join and format values and array of objects to a string in python. Is there any way for me to do that?
url = "https://google.com",
search = "thai food",
search_res = [
{
"restaurant": "Siam Palace",
"rating": "4.5"
},
{
"restaurant": "Bangkok Palace",
"rating": "3.5"
}
]
url = "https://google.com",
search = "indian food",
search_res = [
{
"restaurant": "Taj Palace",
"rating": "2.5"
},
{
"restaurant": "Chennai Express",
"rating": "5.0"
}
]
url = "https://bing.com",
search = "thai food",
search_res = [
{
"restaurant": "Siam Palace",
"rating": "1.5"
},
{
"restaurant": "Bangkok Palace",
"rating": "4.5"
}
]
url = "https://bing.com",
search = "indian food",
search_res = [
{
"restaurant": "Taj Palace",
"rating": "4.5"
},
{
"restaurant": "Chennai Express",
"rating": "3.0"
}
]
我希望能够这样设置值的格式:
I want to be able to format the values as such:
如果我可以使它看起来像这样:
If I could make it look like:
all_data = [{
url = "https://google.com",
results = [{
search = "thai food",
search_res = [{
"restaurant": "Siam Palace",
"rating": "4.5"
}, {
"restaurant": "Bangkok Palace",
"rating": "3.5"
}]
}, {
search = "Indian food",
search_res = [{
"restaurant": "Taj Palace",
"rating": "2.5"
}, {
"restaurant": "CHennai Express",
"rating": "5.0"
}]
}]
}, {
url = "https://bing.com",
results = [{
search = "thai food",
search_res = [{
"restaurant": "Siam Palace",
"rating": "1.5"
}, {
"restaurant": "Bangkok Palace",
"rating": "4.5"
}]
}, {
search = "Indian food",
search_res = [{
"restaurant": "Taj Palace",
"rating": "4.5"
}, {
"restaurant": "CHennai Express",
"rating": "3.0"
}]
}]
}, ]
我这样做是为了加入值:
I did this to join the values:
data = {}
data['url'] = 'https://google.com'
data['search'] = 'thai food'
data['results'] = results
import json
print(json.dumps(data, indent=4)
我的结果是将3个值全部合并在一起,并对每个值重复一次.无论如何,我是否可以将其格式化为上述格式?
My results are joining the 3 values all together and repeats it for each of them. Is there anyway for me to format it in the format mentioned above?
推荐答案
您可以列出并附加每个条目.
You could make a list and append each entry.
all_data = []
data_google = {
'url' = 'https://google.com',
'results' = []
}
data_thai = {}
data_thai['search'] = 'thai food'
data_thai['results'] = results
data_google.append(data_thai)
data_indian = {}
data_indian['search'] = 'indian food'
data_indian['results'] = results
data_google.append(data_indian)
all_data.append(data_google)
...
import json
print(json.dumps(all_data , indent=4)
这篇关于在Python中联接并格式化对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文