寻求Python编码解码方案:生成可被JSON.parse解析的干净JSON数据
寻求通用Python编码方案以生成可被JSON.parse解析的干净JSON数据
我需要找到正确的Python encode()与decode()函数组合,确保无论输入包含何种特殊ASCII、Unicode或emoji字符,最终生成的JSON数据都能被JavaScript的JSON.parse()完全干净地解析。
最初遇到乱码emoji时,我用value.encode('cp1252','backslashreplace').decode('utf-8','backslashreplace')解决了问题,但后续遇到\x92字符时,JSON.parse报“Bad escaped character”错误,临时用replace()处理后,又出现\u011f\x9f\x91\x8c\u011f\x9f\ufffd\xbd这类新的特殊编码字符,导致解析再次失败。
以下是调用API并尝试解码的完整Python代码,以及API原始返回数据和处理后无法解析的JSON示例,希望得到通用解决方案:
# models/api_connector.py from odoo import models, fields, api import requests import base64 import configparser import os class MyAPIConnector(models.Model): _name = 'api.connector' _description = 'API Connector' name = fields.Char('Name') def _generate_auth_header(self): # Read configuration config = configparser.ConfigParser() config_path = os.path.join(os.path.dirname(__file__), '..', 'config.ini') config.read(config_path) # Combine and encode credentials org_name = config.get('api_credentials', 'org_name') secret_key = config.get('api_credentials', 'secret_key') combined_credentials = f"{org_name}:{secret_key}" encoded_credentials = base64.b64encode(combined_credentials.encode()).decode() return f"Basic {encoded_credentials}" def fetch_data(self, zip_code): try: headers = {'Authorization': self._generate_auth_header()} category_pk = '123456789' API_ENDPOINT = f"https://api.myapi.com/v1/partners/discoverylite/pros?zip_code={zip_code}&category_pk={category_pk}&utm_source=myCompany" response = requests.get(API_ENDPOINT, headers=headers) response_text = response.text # Decoding and re-encoding the response text decoded_text = response_text.encode('cp1252', 'backslashreplace').decode('utf-8', 'backslashreplace') decoded_text = decoded_text.replace('\\x92', "’") return decoded_text except Exception as e: _logger.error(f"Error: {e}")
API原始返回数据(可被JSON.parse正常解析):
{ "results": [{ "service_id": "490803031657299972", "business_name": "Jay Contractors LLC", "rating": 4.972222222222222, "num_reviews": 36, "years_in_business": 1, "num_hires": 87, "thumbtack_url": "https://www.thumbtack.com/pa/lansdowne/handyman/jay-contractors-llc/service/490803031657299972?category_pk=151436204227846419\u0026utm_medium=partnership\u0026utm_source=cma-hewn\u0026zip_code=19701", "image_url": "https://production-next-images-cdn.thumbtack.com/i/490934068026425349/desktop/standard/thumb", "background_image_url": "https://production-next-images-cdn.thumbtack.com/i/319588452476190788/small/standard/hero", "featured_review": "Went and above and beyond to expose and fix other poorly done installations 👌�", "quote": { "starting_cost": 5000, "cost_unit": "on-site estimate" }, "introduction": "My focus is quality, and dedication to the job. I take pride in every job, from start to finish. Always go for 100% satisfaction by client and see them smiling after the work is completed.\n\nPlease keep in mind if your using the instant book feature, it means your hiring me for my services and if you decide to cancel later on there will be a charge.\n\nAccept Cash, Cashapp, Zelle, and Venmo.\nNo Checks please.\n\nLicensed and Insured", "pills": ["popular", "licensed"], "location": "Bear, DE", "similar_jobs_done": 1, "license_verified": true, "num_of_employees": 2, "has_background_check": true, "iframe_url": "" }] }
处理后无法被JSON.parse解析的JSON数据:
{ "results": [{ "service_id": "490803031657299972", "business_name": "Jay Contractors LLC", "rating": 4.972222222222222, "num_reviews": 36, "years_in_business": 1, "num_hires": 87, "thumbtack_url": "https://www.thumbtack.com/pa/lansdowne/handyman/jay-contractors-llc/service/490803031657299972?category_pk=151436204227846419\u0026utm_medium=partnership\u0026utm_source=cma-hewn\u0026zip_code=19701", "image_url": "https://production-next-images-cdn.thumbtack.com/i/490934068026425349/desktop/standard/thumb", "background_image_url": "https://production-next-images-cdn.thumbtack.com/i/319588452476190788/small/standard/hero", "featured_review": "Went and above and beyond to expose and fix other poorly done installations \u011f\x9f\x91\x8c\u011f\x9f\ufffd\xbd", "quote": { "starting_cost": 5000, "cost_unit": "on-site estimate" }, "introduction": "My focus is quality, and dedication to the job. I take pride in every job, from start to finish. Always go for 100% satisfaction by client and see them smiling after the work is completed.\n\nPlease keep in mind if your using the instant book feature, it means your hiring me for my services and if you decide to cancel later on there will be a charge.\n\nAccept Cash, Cashapp, Zelle, and Venmo.\nNo Checks please.\n\nLicensed and Insured", "pills": ["popular", "licensed"], "location": "Bear, DE", "similar_jobs_done": 1, "license_verified": true, "num_of_employees": 2, "has_background_check": true, "iframe_url": "" }] }
内容的提问来源于stack exchange,提问作者velkoon
相关产品推荐
相关产品推荐

