【问题标题】:Mysql json.dump() line break indentation for viewingMysql json.dump() 换行缩进查看
【发布时间】:2020-07-29 15:37:27
【问题描述】:

我正在使用以下代码行来执行和打印我的 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)

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

【问题讨论】:

    标签: python mysql sql json python-3.x


    【解决方案1】:

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

    希望能帮到你。

    【讨论】:

    • 非常感谢!我也试试熊猫的方式。
    • 是的,使用 pandas 会更容易。没问题
    • 每次我尝试运行这个:>> list_a=json_string.split(',') 它给我一个错误说:for message_part in text.strip().split("\n\ n"): AttributeError: 'list' 对象没有属性 'strip'
    • 好吧,这很奇怪,您能否分享您的完整代码。也许我明白那会发生什么?也许在 GitHub 或类似的地方。
    • 好的,我认为您的字符串在某种程度上是不正确的。请您打印字符串并再次共享该输出,好吗?或者尝试添加 list_a=str(json_string).split(',')。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2018-07-17
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多