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

如何从键值对结构的Object对象中提取指定属性值

取值操作步骤

你当前定义的obj是字符串类型,且内容不符合标准JSON规范,无法直接提取属性,需要先做格式转换再解析取值,操作流程如下:

  • 第一步:将非标准字符串转换为标准JSON格式
    依次完成3处字符替换:
    1. 把所有=替换为:
    2. 给所有键名(冒号左侧的标识符)包裹双引号
    3. 给所有字符串类型的属性值(非数字的值)包裹双引号
      转换完成后你会得到符合JSON规范的字符串:
      [{"Branch":60, "Currency":"cv", "Id":"abv", "RemainingAmount":20.45},{"Branch":60, "Currency":"INJ", "Id":"bnb", "RemainingAmount":120.0}]
  • 第二步:解析标准JSON为可操作的对象/集合
    不同开发语言的解析逻辑一致,均可以调用对应语言的JSON解析工具将JSON字符串转为数组/列表结构,以下为两种常用语言的代码示例:

    Java示例(用Fastjson做解析)

    // 原始字符串
    String originalStr = "[{Branch=60, Currency=cv, Id=abv, RemainingAmount=20.45},{Branch=60, Currency=INJ, Id=bnb, RemainingAmount=120.0}]";
    // 格式转换
    String standardJson = originalStr.replace("=", ":")
            .replaceAll("(\\w+)(?=:)", "\"$1\"")
            .replaceAll(":(\\D[^,}]*)", ":\"$1\"");
    // 解析为Map列表
    List<Map<String, Object>> dataList = com.alibaba.fastjson.JSON.parseArray(standardJson, Map.class);
    // 取值示例:获取第一个元素的RemainingAmount
    Double firstRemaining = (Double) dataList.get(0).get("RemainingAmount");
    // 取值示例:获取第二个元素的Id
    String secondId = (String) dataList.get(1).get("Id");
    

    JavaScript示例

    // 原始字符串
    const originalStr = "[{Branch=60, Currency=cv, Id=abv, RemainingAmount=20.45},{Branch=60, Currency=INJ, Id=bnb, RemainingAmount=120.0}]";
    // 格式转换
    const standardJson = originalStr.replace(/=/g, ':')
      .replace(/(\w+)(?=:)/g, '"$1"')
      .replace(/:(\D[^,}]*)/g, ':"$1"');
    // 解析为对象数组
    const dataList = JSON.parse(standardJson);
    // 取值示例:获取第一个元素的Currency
    const firstCurrency = dataList[0].Currency;
    // 取值示例:获取第二个元素的RemainingAmount
    const secondRemaining = dataList[1].RemainingAmount;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:30:03