You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Bitbucket API返回的纯文本响应转换为JSON对象?

转换Bitbucket纯文本响应为键值对JSON对象

核心处理逻辑

先将接口返回的纯文本按换行分割为单行,逐行提取键=值格式的内容,转换值的类型为数字,最后组装成目标格式的字典(JSON对象)。

Python实现示例

# 接口返回的纯文本内容
response_text = "a=90\nb=70"

result = {}
# 按换行拆分所有行
lines = response_text.split('\n')

for line in lines:
    # 跳过空行
    cleaned_line = line.strip()
    if not cleaned_line:
        continue
    # 按第一个等号拆分键值,避免值中包含等号的情况
    key_part, value_part = cleaned_line.split('=', 1)
    # 键转为小写(按需可移除),值转为整数
    result[key_part.strip().lower()] = int(value_part.strip())

print(result)  # 输出: {'a': 90, 'b': 70}

JavaScript实现示例

// 接口返回的纯文本内容
const responseText = "a=90\nb=70";

const result = {};
const lines = responseText.split('\n');

lines.forEach(line => {
    const cleanedLine = line.trim();
    if (!cleanedLine) return;
    // 拆分键值对
    const [key, value] = cleanedLine.split('=', 1);
    result[key.trim().toLowerCase()] = parseInt(value.trim(), 10);
});

console.log(result); // 输出: {a: 90, b: 70}

扩展适配说明

  • 如果值可能是浮点数,将Python的int()替换为float(),JavaScript的parseInt()替换为parseFloat()
  • 不需要统一键的大小写时,移除.lower()(Python)或.toLowerCase()(JavaScript)
  • 若文本中存在非键=值格式的行,可添加额外判断逻辑过滤无效行

内容的提问来源于stack exchange,提问作者annoymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 15:45:12