Mysql json.dump()换行缩进以供查看

Zaid Alvi:

我正在使用以下代码行从我的sql数据库执行和打印数据。由于某种原因,这是唯一对我有用的命令。

json_string = json.dumps(location_query_1)

我的问题是,当我打印json_string时,它以以下格式显示数据:

在此处输入图片说明

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)

我该怎么办,数据以垂直列表格式(换行缩进)显示,并且没有括号和引号?谢谢

SebNik:

首先,您是否尝试过将数据读入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?

希望我能帮上忙。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章