Python Mysql json.dump()用于查看的换行缩进
我使用以下代码行从sql数据库执行和打印数据。出于某种原因,这是唯一对我有效的命令Python Mysql json.dump()用于查看的换行缩进,python,mysql,sql,json,python-3.x,Python,Mysql,Sql,Json,Python 3.x,我使用以下代码行从sql数据库执行和打印数据。出于某种原因,这是唯一对我有效的命令 json_string = json.dumps(location_query_1) 我的问题是,当我打印json_字符串时,它以以下格式显示数据: Actions.py代码: class FindByLocation(Action): def name(self) -> Text: return "action_find_by_location" def run (s
json_string = json.dumps(location_query_1)
我的问题是,当我打印json_字符串时,它以以下格式显示数据:
Actions.py代码:
class FindByLocation(Action):
def name(self) -> Text:
return "action_find_by_location"
def run (self, dispatcher: CollectingDispatcher,
tracker: Tracker,
doman: Dict[Text, Any])-> List[Dict[Text,Any]]:
global flag
location = tracker.get_slot("location")
price = tracker.get_slot("price")
cuisine = tracker.get_slot("cuisine")
print("In find by Location")
print(location)
location_query = "SELECT Name FROM Restaurant WHERE Location = '%s' LIMIT 5" % location
location_count_query = "SELECT COUNT(Name) FROM Restaurant WHERE Location = '%s'" % location
location_query_1 = getData(location_query)
location_count_query_1 = getData(location_count_query)
if not location_query_1:
flag = 1
sublocation_view_query = "CREATE VIEW SublocationView AS SELECT RestaurantID, Name, PhoneNumber, Rating, PriceRange, Location, Sublocation FROM Restaurant WHERE Sublocation = '%s'"%(location)
sublocation_view = getData(sublocation_view_query)
dispatcher.utter_message(text="یہ جگہ کس ایریا میں ہے")
else:
flag = 0
if cuisine is None and price is None:
json_string = json.dumps(location_query_1)
print(isinstance(json_string, str))
print("Check here")
list_a=json_string.split(',')
remove=["'",'"','[',']']
for i in remove:
list_a=[s.replace(i, '') for s in list_a]
dispatcher.utter_message(text="Restaurants in Location only: ")
dispatcher.utter_message(list_a)
如果数据以垂直列表格式(新行缩进)显示,并且没有括号和引号,我应该怎么做?谢谢首先,您是否尝试过将数据读入pandas对象?我已经使用sqlite数据库完成了一些程序,这对我很有用:
df = pd.read_sql_query("SELECT * FROM {}".format(self.tablename), conn)
现在转到字符串格式部分:
# this code should do the work for you
# first of all we have our string a like yours
a="[['hallo'],['welt'],['kannst'],['du'],['mich'],['hoeren?']]"
# now we split the string into a list on every ,
list_a=a.split(',')
# this is our list with chars we want to remove
remove=["'",'"','[',']']
# now we replace all elements step by step with nothing
for i in remove:
list_a=[s.replace(i, '') for s in list_a]
print(list_a)
for z in list_a:
print(z)
然后输出为:
['hallo', 'welt', 'kannst', 'du', 'mich', 'hoeren?']
hallo
welt
kannst
du
mich
hoeren?
希望我能帮忙。非常感谢!我也会尝试熊猫的方式。是的,有了熊猫会更容易。没有问题每次我试着运行这个:>>list_a=json_string.split(',')它会给我一个错误:对于text.strip().split(“\n\n”):AttributeError:'list'对象没有属性'strip',好奇怪,你可以分享你的完整代码吗。也许我明白会发生什么?也许在GitHub上或者类似的东西上。好吧,我觉得你的字符串有点不对劲。你能把这个字符串打印出来,然后再分享一下吗?或者尝试添加list_a=str(json_string).split(',')。