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

如何用JavaScript提取JSON中首个包含'amogus'的字符串?

获取JSON中首个包含指定字符串的元素

Python 实现

首先确保你的JSON格式合法(键名必须用双引号),然后通过解析JSON并遍历数组找到目标元素:

import json

# 标准JSON格式的字符串
json_content = '{"stuff": ["hosds29083", "amogus1208", "amogus1213"]}'
parsed_data = json.loads(json_content)

# 遍历数组,返回第一个包含'amogus'的元素
target_item = None
for item in parsed_data['stuff']:
    if 'amogus' in item:
        target_item = item
        break

print(repr(target_item))  # 输出: 'amogus1208'

如果是从本地JSON文件读取:

import json

with open('your_file.json', 'r') as f:
    parsed_data = json.load(f)

for item in parsed_data['stuff']:
    if 'amogus' in item:
        print(repr(item))
        break

JavaScript 实现(浏览器/Node.js)

利用数组的find方法直接匹配第一个符合条件的元素:

// 解析后的JSON对象(如果是字符串先通过JSON.parse转换)
const data = {"stuff": ["hosds29083", "amogus1208", "amogus1213"]};

const firstMatch = data.stuff.find(item => item.includes('amogus'));
console.log(firstMatch); // 输出: amogus1208

Node.js中读取文件的写法:

const fs = require('fs');

const jsonContent = fs.readFileSync('your_file.json', 'utf8');
const data = JSON.parse(jsonContent);

const firstMatch = data.stuff.find(item => item.includes('amogus'));
console.log(firstMatch);

注意事项

  • 原始示例的JSON格式不规范,JSON要求所有键名必须用双引号包裹,实际处理时要保证输入是标准JSON,否则解析会报错。
  • 上述代码都会返回数组中第一个包含'amogus'的元素,一旦找到就停止遍历,保证效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:01:00