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

JavaScript提取JSON对象键名存入字符串数组的字符串处理逻辑问题

Fixing JSON Key Extraction to String Array

Hey there! Let's sort out this JSON key extraction issue you're dealing with.

First off, relying on manual string slicing with str.substring() to grab keys by hunting for quotes is super error-prone. JSON has all kinds of edge cases that break this approach—think nested objects, escaped quotes in string values, arrays, or even whitespace formatting variations. That's why your output is coming out wonky and unrecognizable.

The Reliable, Built-in Solution

Instead of reinventing the wheel, use JavaScript's native tools to handle JSON properly:

  1. Parse the JSON string into a JavaScript object with JSON.parse()
  2. Extract all top-level keys using Object.keys()

Here's a quick example:

// Your raw JSON string
const jsonString = '{"username": "HshMsh", "email": "example@test.com", "settings": {"notifications": true}}';

// Step 1: Parse the JSON into an object
const parsedObj = JSON.parse(jsonString);

// Step 2: Extract keys into an array
const keyArray = Object.keys(parsedObj);

console.log(keyArray); // Output: ["username", "email", "settings"]

Need Nested Keys Too?

If you need to capture keys from nested objects as well, a simple recursive function will do the trick:

function extractAllKeys(obj) {
  let keys = [];
  for (const key of Object.keys(obj)) {
    keys.push(key);
    // Check if the value is a non-null, non-array object
    if (typeof obj[key] === 'object' && obj[key] !== null && !Array.isArray(obj[key])) {
      keys = keys.concat(extractAllKeys(obj[key]));
    }
  }
  return keys;
}

// Usage
const allKeys = extractAllKeys(parsedObj);
console.log(allKeys); // Output: ["username", "email", "settings", "notifications"]

Why Your Original Approach Fails

Manual string slicing doesn't account for JSON's syntax rules:

  • Escaped quotes like {"message": "He said \"Hi!\""} will throw off your quote position calculations
  • Nested objects add extra layers of brackets/quotes that your substring logic can't properly navigate
  • Whitespace (like newlines or spaces between keys/values) will break your index counting

Stick to native JSON parsing—it's designed to handle all these edge cases out of the box.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:49:47