问题
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)
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?
回答1:
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)
来源:https://stackoverflow.com/questions/59260047/join-and-format-array-of-objects-in-python