代码之家  ›  专栏  ›  技术社区  ›  Rasik

如何在Python中将带有单引号的无效JSON字符串转换为有效JSON?

  •  -3
  • Rasik  · 技术社区  · 1 年前

    我不小心在数据库中保存了一个类似JSON的字符串,该字符串使用单引号而不是双引号,JSON格式化程序无法将其识别为有效的JSON。这是我的字符串:

    import json
    
    json_string = """
    {'author': 'Hebbars Kitchen', 'canonical_url': 'https://hebbarskitchen.com/til-chikki-recipe-sesame-chikki-gajak/', 'category': 'sweet', 'cook_time': 10, 'cuisine': 'Indian', 'description': 'easy til chikki recipe | sesame chikki recipe | til ki chikki or til gajak', 'host': 'hebbarskitchen.com', 'image': 'https://hebbarskitchen.com/wp-content/uploads/mainPhotos/til-chikki-recipe-sesame-chikki-recipe-til-ki-chikki-or-til-gajak-2.jpeg', 'ingredient_groups': [{'ingredients': ['1 cup sesame / til (white)', '1 tsp ghee / clarified butter', '1 cup jaggery / gud'], 'purpose': None}], 'ingredients': ['1 cup sesame / til (white)', '1 tsp ghee / clarified butter', '1 cup jaggery / gud'], 'instructions': 'firstly in a pan dry roast 1 cup sesame on low flame till it splutters.\nnow in another kadai heat 1 tsp ghee and add 1 cup jaggery.\nkeep stirring on medium flame till the jaggery melts completely. alternatively, use sugar, if you do not prefer jaggery.\nboil the jaggery syrup on low flame till the syrup turns glossy and thickens.\ncheck the consistency, by dropping syrup into a bowl of water, it should form hard ball and cut with a snap sound. else boil for another minute and check.\nsimmer the flame add add roasted sesame seeds.\nstir well making sure jaggery syrup coats well.\nimmediately pour the mixture over butter paper or onto steel plate greased with ghee. be quick else the mixture turns hard and will be difficult to set.\nget together forming a block, be careful as the mixture will be very hot.\nnow using a rolling pin roll the slightly thick block.\nallow to cool for a minute, and when its still warm cut into pieces.\nlastly, serve til chikki once cooled completely, or store in a airtight container and serve for a month.', 'instructions_list': ['firstly in a pan dry roast 1 cup sesame on low flame till it splutters.', 'now in another kadai heat 1 tsp ghee and add 1 cup jaggery.', 'keep stirring on medium flame till the jaggery melts completely. alternatively, use sugar, if you do not prefer jaggery.', 'boil the jaggery syrup on low flame till the syrup turns glossy and thickens.', 'check the consistency, by dropping syrup into a bowl of water, it should form hard ball and cut with a snap sound. else boil for another minute and check.', 'simmer the flame add add roasted sesame seeds.', 'stir well making sure jaggery syrup coats well.', 'immediately pour the mixture over butter paper or onto steel plate greased with ghee. be quick else the mixture turns hard and will be difficult to set.', 'get together forming a block, be careful as the mixture will be very hot.', 'now using a rolling pin roll the slightly thick block.', 'allow to cool for a minute, and when its still warm cut into pieces.', 'lastly, serve til chikki once cooled completely, or store in a airtight container and serve for a month.'], 'language': 'en-US', 'nutrients': {}, 'prep_time': 5, 'ratings': 5.0, 'ratings_count': 196, 'site_name': "Hebbar's Kitchen", 'title': 'til chikki recipe | sesame chikki recipe | til ki chikki or til gajak', 'total_time': 15, 'yields': '24 servings'}
    """
    
    formatted_json = json.dumps(json_string)
    
    print(formatted_json)
    

    该字符串包含单引号而不是双引号,因此它是无效的JSON。我尝试使用json.dumps()来格式化它,但这只是将字符串转换为另一个json字符串,而不是解决问题。

    我也试着用 ast.literal_eval demjson3 ,似乎什么都没用。

    使用 ast.literal_eval()

    import json
    
    # Assume your JSON string is stored in a variable called 'json_string'
    json_string = """
    {'author': 'Hebbars Kitchen', 'canonical_url': 'https://hebbarskitchen.com/til-chikki-recipe-sesame-chikki-gajak/', 'category': 'sweet', 'cook_time': 10, 'cuisine': 'Indian', 'description': 'easy til chikki recipe | sesame chikki recipe | til ki chikki or til gajak', 'host': 'hebbarskitchen.com', 'image': 'https://hebbarskitchen.com/wp-content/uploads/mainPhotos/til-chikki-recipe-sesame-chikki-recipe-til-ki-chikki-or-til-gajak-2.jpeg', 'ingredient_groups': [{'ingredients': ['1 cup sesame / til (white)', '1 tsp ghee / clarified butter', '1 cup jaggery / gud'], 'purpose': None}], 'ingredients': ['1 cup sesame / til (white)', '1 tsp ghee / clarified butter', '1 cup jaggery / gud'], 'instructions': 'firstly in a pan dry roast 1 cup sesame on low flame till it splutters.\nnow in another kadai heat 1 tsp ghee and add 1 cup jaggery.\nkeep stirring on medium flame till the jaggery melts completely. alternatively, use sugar, if you do not prefer jaggery.\nboil the jaggery syrup on low flame till the syrup turns glossy and thickens.\ncheck the consistency, by dropping syrup into a bowl of water, it should form hard ball and cut with a snap sound. else boil for another minute and check.\nsimmer the flame add add roasted sesame seeds.\nstir well making sure jaggery syrup coats well.\nimmediately pour the mixture over butter paper or onto steel plate greased with ghee. be quick else the mixture turns hard and will be difficult to set.\nget together forming a block, be careful as the mixture will be very hot.\nnow using a rolling pin roll the slightly thick block.\nallow to cool for a minute, and when its still warm cut into pieces.\nlastly, serve til chikki once cooled completely, or store in a airtight container and serve for a month.', 'instructions_list': ['firstly in a pan dry roast 1 cup sesame on low flame till it splutters.', 'now in another kadai heat 1 tsp ghee and add 1 cup jaggery.', 'keep stirring on medium flame till the jaggery melts completely. alternatively, use sugar, if you do not prefer jaggery.', 'boil the jaggery syrup on low flame till the syrup turns glossy and thickens.', 'check the consistency, by dropping syrup into a bowl of water, it should form hard ball and cut with a snap sound. else boil for another minute and check.', 'simmer the flame add add roasted sesame seeds.', 'stir well making sure jaggery syrup coats well.', 'immediately pour the mixture over butter paper or onto steel plate greased with ghee. be quick else the mixture turns hard and will be difficult to set.', 'get together forming a block, be careful as the mixture will be very hot.', 'now using a rolling pin roll the slightly thick block.', 'allow to cool for a minute, and when its still warm cut into pieces.', 'lastly, serve til chikki once cooled completely, or store in a airtight container and serve for a month.'], 'language': 'en-US', 'nutrients': {}, 'prep_time': 5, 'ratings': 5.0, 'ratings_count': 196, 'site_name': "Hebbar's Kitchen", 'title': 'til chikki recipe | sesame chikki recipe | til ki chikki or til gajak', 'total_time': 15, 'yields': '24 servings'}
    """
    
    # Dump the JSON with proper formatting
    formatted_json = ast.literal_eval(json_string)
    
    print(formatted_json)
    

    我遇到错误

      File <unknown>:2
        {'author': 'Hebbars Kitchen', 'canonical_url': 'https://hebbarskitchen.com/til-chikki-recipe-sesame-chikki-gajak/', 'category': 'sweet', 'cook_time': 10, 'cuisine': 'Indian', 'description': 'easy til chikki recipe | sesame chikki recipe | til ki chikki or til gajak', 'host': 'hebbarskitchen.com', 'image': 'https://hebbarskitchen.com/wp-content/uploads/mainPhotos/til-chikki-recipe-sesame-chikki-recipe-til-ki-chikki-or-til-gajak-2.jpeg', 'ingredient_groups': [{'ingredients': ['1 cup sesame / til (white)', '1 tsp ghee / clarified butter', '1 cup jaggery / gud'], 'purpose': None}], 'ingredients': ['1 cup sesame / til (white)', '1 tsp ghee / clarified butter', '1 cup jaggery / gud'], 'instructions': 'firstly in a pan dry roast 1 cup sesame on low flame till it splutters.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        ^
    SyntaxError: unterminated string literal (detected at line 2)
    
    3 回复  |  直到 1 年前
        1
  •  1
  •   SIGHUP    1 年前

    嵌入的换行符将导致literal_val失败。

    您可以简单地删除它们并获得所需的结果,如下所示:

    import ast
    import json
    d = ast.literal_eval(json_string.replace("\n", "")
    print(json.dumps(d, indent=2))
    

    因此 d 将引用有效的Python词典

        2
  •  0
  •   Deeku    1 年前

    试试这个

      import ast
      import json
    
      # Correct the string to properly use triple quotes
      json_string = """{'author': 'Hebbars Kitchen'}"""
    
      try:
      # Step 1: Parse the string into a Python dictionary
      data = ast.literal_eval(json_string)
    
      # Step 2: Serialize the dictionary into a valid JSON string
      valid_json = json.dumps(data)
    
      # Step 3: Print or update the database with `valid_json`
      print(valid_json)
    
      # Save to database.....
     
      except (ValueError, SyntaxError) as e:
         print("Error parsing the string:", e)
    

    ast.leral_eval()的使用

    安全性:ast.leall_eval()只计算安全的文本和表达式,这些文本和表达式通常存在于JSON等数据格式中(例如字符串、数字、列表、字典)。

    安全性:对不受信任的输入使用eval()可能是危险的,因为它可以执行任意代码。ast.leral_eval()通过限制它可以计算的表达式类型来避免这种风险。

        3
  •  0
  •   Konan    1 年前

    要修复带有单引号的类JSON字符串并将其转换为有效的JSON格式:

    首先将单引号替换为双引号。 使用 str.replace() 将单引号更改为双引号。

    然后验证结果。 使用 json.loads() 检查字符串是否为有效的JSON。

    这里有一个简短的例子:

    import json
    
    # Original string with single quotes
    json_string = "{'key': 'value'}"
    
    # Replace single quotes with double quotes
    valid_json_string = json_string.replace("'", '"')
    
    # Validate and format the JSON
    try:
        json_data = json.loads(valid_json_string)
        formatted_json = json.dumps(json_data, indent=4)
        print(formatted_json)
    except json.JSONDecodeError as e:
        print(f"JSON decoding failed: {e}")
    

    此代码示例将单引号替换为双引号,然后尝试解析JSON。如果解析成功,它将打印格式化的JSON。如果出现问题,它会捕获错误并打印错误消息。