在JavaScript中转换为JSON

问题描述 投票:0回答:1
应用程序应:

  • 从.txt文件阅读数据(例如,

    weather:blabla:sunny

    )。
    

  • 将其转换为.json.
  • 问题:
在.txt→.json转换期间,最后一个部分(例如,“ Sunny”)被切断。

.txt格式:
在第一个之前的键:,第二个之后的值:,介于两者之间的一切都是无关的。

条件:


没有外部软件,敏感数据。

link键到应用程序:

    Google驱动器
  • 运行:在VS代码中→终端→NPX Electron。
Exped.txt格式:

天气: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"
javascript node.js json electron txt
1个回答
0
投票

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(":")

获取最后一次出现 - 这是我们找到值的地方。 两者之间的全部内容被忽略了

,因为它无关紧要。

示例案例:

  1. 输入
    输出json
  2. 
    
  3. lastIndexOf(":")
"weather:blabla:sunny"

{ "weather": "sunny" }这种方法可确保无论介于两者之间,我们总是捕获正确的钥匙和价值。
"temperature:ignore:this:hot"
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.