weather:blabla:sunny
)。
.txt格式:
在第一个之前的键:,第二个之后的值:,介于两者之间的一切都是无关的。
link键到应用程序:
天气:Blabla:阳光明媚或(天气:Blabla; Blabla:Sunny)
问题如何制作,以便在第二个':'它将数据读取到json之后,而txt文件的其余部分正正确地读取?
代码:
// Function to convert TXT file content to JSON
function convertToJson(text) {
console.log("Input data:", text); // For debugging
const lines = text.split('\n').filter(line => line.trim());
const result = {};
for (const line of lines) {
console.log("Processed line:", line); // For debugging
// Skip empty lines
if (!line.trim()) continue;
// Find the position of the first colon
const firstColonIndex = line.indexOf(':');
// If there’s no colon, skip to the next line
if (firstColonIndex === -1) continue;
// Extract the key (before the first colon)
const key = line.substring(0, firstColonIndex).trim();
// Extract the full value after the first colon
const fullValue = line.substring(firstColonIndex + 1);
console.log(`Found key: "${key}", value: "${fullValue}"`); // For debugging
// Save to the result object
result[key] = fullValue.trim();
}
console.log("JSON result:", result); // For debugging
return result;
}
// Test
const testData = "weather:sunny:flower";
const result = convertToJson(testData);
console.log(JSON.stringify(result, null, 2));
看起来您当前的逻辑正在抓住所有内容在第一个结肠(':')
"weather:sunny:flower"
而不是仅仅捕获
"sunny:flower"
Solution: 您需要:
✅从第一个colon
之前提取钥匙✅在最后一个结肠之后从last段中提取值 ✅忽略所有之间的一切 there是您
"flower"
函数的校正版本:
convertToJson
修复的解释:
function convertToJson(text) {
console.log("Input data:", text); // Debugging
const lines = text.split("\n").filter(line => line.trim()); // Remove empty lines
const result = {};
for (const line of lines) {
console.log("Processing line:", line);
const firstColonIndex = line.indexOf(":");
const lastColonIndex = line.lastIndexOf(":");
// Skip invalid lines
if (firstColonIndex === -1 || lastColonIndex === -1 || firstColonIndex === lastColonIndex) continue;
// Extract key (everything before the first ':')
const key = line.substring(0, firstColonIndex).trim();
// Extract value (everything after the last ':')
const value = line.substring(lastColonIndex + 1).trim();
console.log(`Key: "${key}", Value: "${value}"`); // Debugging
result[key] = value;
}
console.log("JSON Result:", result); // Debugging
return result;
}
// Test case
const testData = "weather:blabla:sunny";
const result = convertToJson(testData);
console.log(JSON.stringify(result, null, 2));
获取第一次出现 - 这是我们找到钥匙的地方。
indexOf(":")
获取最后一次出现 - 这是我们找到值的地方。 两者之间的全部内容被忽略了
,因为它无关紧要。
示例案例:
lastIndexOf(":")
"weather:blabla:sunny"
{ "weather": "sunny" }
这种方法可确保无论介于两者之间,我们总是捕获正确的钥匙和价值。
"temperature:ignore:this:hot" |
|
---|---|