Conversor de Texto para JSON
Converta linhas de texto simples em arrays JSON, objetos ou analise pares chave:valor. Múltiplos modos de conversão.
Perguntas Frequentes
Implementação de Código
# Text to JSON Conversion Utilities
import json
def lines_to_array(text: str, skip_empty: bool = True, trim: bool = True) -> list:
lines = text.split("\n")
if trim:
lines = [l.strip() for l in lines]
if skip_empty:
lines = [l for l in lines if l]
return lines
def lines_to_objects(text: str, key: str = "text", skip_empty: bool = True) -> list:
lines = lines_to_array(text, skip_empty)
return [{key: line} for line in lines]
def keyvalue_to_object(text: str, trim: bool = True) -> dict:
result = {}
for line in text.split("\n"):
if trim:
line = line.strip()
for sep in [":", "="]:
idx = line.find(sep)
if idx > 0:
k = line[:idx].strip()
v = line[idx+1:].strip()
result[k] = v
break
return result
def csv_to_json(text: str, trim: bool = True) -> list:
lines = text.split("\n")
if not lines:
return []
headers = [h.strip() if trim else h for h in lines[0].split(",")]
result = []
for line in lines[1:]:
if not line.strip():
continue
values = [v.strip() if trim else v for v in line.split(",")]
result.append({headers[i]: values[i] if i < len(values) else "" for i in range(len(headers))})
return result
# Examples
text = "apple\nbanana\ncherry"
print(json.dumps(lines_to_array(text), indent=2))
kv_text = "name: Alice\nage: 30\ncity: London"
print(json.dumps(keyvalue_to_object(kv_text), indent=2))
csv_text = "name,age,city\nAlice,30,London\nBob,25,Paris"
print(json.dumps(csv_to_json(csv_text), indent=2))Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.