JavaScript提取JSON对象键名存入字符串数组的字符串处理逻辑问题
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:
- Parse the JSON string into a JavaScript object with
JSON.parse() - 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

