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

如何从微软翻译文本API的JSON响应中提取指定翻译文本?

如何从微软翻译API响应中获取指定翻译文本?

嘿,我来帮你搞定这个问题!咱们先拆解下你拿到的JSON响应结构,这样你能一目了然怎么定位到目标内容:

[{"detectedLanguage":{"language":"de","score":1.0},"translations":[{"text":"Heute ist ein schöner Tag","to":"de"},{"text":"Today is a beautiful day","to":"en"}]}]

这个响应本质是一个包含单个对象的数组,这个对象里的translations字段又是一个数组,里面的第二个元素(数组索引从0开始计数,所以对应索引1)就是你要的英文翻译结果。

下面给你举两个最常用编程语言的实现方式:

Python 实现

先把JSON字符串反序列化为Python字典,然后通过索引和键名直接访问:

import json

# 你的API响应JSON字符串
response_json = '[{"detectedLanguage":{"language":"de","score":1.0},"translations":[{"text":"Heute ist ein schöner Tag","to":"de"},{"text":"Today is a beautiful day","to":"en"}]}]'

# 反序列化JSON为Python数据结构
response_data = json.loads(response_json)

# 定位并获取目标文本
target_text = response_data[0]['translations'][1]['text']
print(target_text)  # 输出结果: Today is a beautiful day

C# 实现

先定义和JSON结构匹配的数据模型,再用序列化库完成反序列化:

using System;
using System.Text.Json;

// 定义匹配JSON结构的数据模型
public class TranslationResponse
{
    public DetectedLanguage DetectedLanguage { get; set; }
    public Translation[] Translations { get; set; }
}

public class DetectedLanguage
{
    public string Language { get; set; }
    public double Score { get; set; }
}

public class Translation
{
    public string Text { get; set; }
    public string To { get; set; }
}

class Program
{
    static void Main()
    {
        string responseJson = @"[{""detectedLanguage"":{""language"":""de"",""score"":1.0},""translations"":[{""text"":""Heute ist ein schöner Tag"",""to"":""de""},{""text"":""Today is a beautiful day"",""to"":""en""}]}]";
        
        // 反序列化JSON为对象数组
        TranslationResponse[] responses = JsonSerializer.Deserialize<TranslationResponse[]>(responseJson);
        
        // 定位并获取目标文本
        string targetText = responses[0].Translations[1].Text;
        Console.WriteLine(targetText); // 输出结果: Today is a beautiful day
    }
}

核心逻辑其实就三步:

  • 先定位到响应数组的第一个元素(你的API返回的数组里只有一个对象)
  • 然后进入该对象下的translations数组,取索引为1的元素
  • 最后提取这个元素里的text字段值,就是你要的内容啦

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:02:52