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

如何将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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:48:31