如何将JSON数组字符串转换为数组并移除空元素?
Got it, let's work through this problem together. You've got a JSON array string full of empty values and want to convert it into a semicolon-separated string of only the non-empty entries. Here are clean, tested implementations in two widely used languages:
JavaScript Solution
This approach uses built-in JSON parsing and array methods to get the job done in just a few lines:
// Your input JSON string const jsonString = '["", "abc", "", "def", "", "mno", "", "", "", "", ""]'; // Step 1: Parse the JSON string into a JavaScript array const originalArray = JSON.parse(jsonString); // Step 2: Filter out empty strings (empty strings are "falsy" in JS, so this works) const filteredArray = originalArray.filter(item => item); // Step 3: Join the remaining items with semicolons const finalResult = filteredArray.join(';'); console.log(finalResult); // Output: "abc;def;mno"
If you need to handle strings with only whitespace (like " ") as empty, adjust the filter condition to item => item.trim() !== '' to make it more robust.
Python Solution
Python's JSON module and list comprehensions make this equally straightforward:
import json # Your input JSON string json_string = '["", "abc", "", "def", "", "mno", "", "", "", "", ""]' # Step 1: Parse the JSON string into a Python list original_list = json.loads(json_string) # Step 2: Filter out empty strings using a list comprehension filtered_list = [item for item in original_list if item] # Step 3: Join the filtered list with semicolons final_result = ';'.join(filtered_list) print(final_result) # Output: abc;def;mno
Similarly, to account for whitespace-only strings, update the condition to if item.strip() instead of just if item.
Both solutions are efficient, readable, and handle exactly the input you provided. Let me know if you need an implementation in another language!
内容的提问来源于stack exchange,提问作者John

