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

JSON解析返回字符串而非数组及CSV转对象实现问题

Let's break down and solve both of your issues step by step:

Problem 1: JSON Parsing Returns String Instead of Expected Array

Common Causes & Fixes

  • Double-stringified data: If you stored the array in localStorage by converting it to a string (with JSON.stringify()), but accidentally stringified it a second time, parsing once will only return the original string—not the array.
  • Forgot to parse when retrieving: If you saved the array as a string but didn’t use JSON.parse() when pulling it from localStorage, you’ll end up with the raw string value.
  • Incorrect data source: The input being parsed might already be a string representation of an array (e.g., "[\"1\",\"2\"]" instead of the actual array ["1","2"]).

Example Fix

If you stored the array correctly:

const myArray = ["1", "2", "3"];
localStorage.setItem("myData", JSON.stringify(myArray));

Retrieve and parse it properly to get the array:

const storedData = localStorage.getItem("myData");
const parsedArray = JSON.parse(storedData); // This will be your expected array

If you accidentally double-stringified the data, parse twice to fix it:

const parsedTwice = JSON.parse(JSON.parse(storedData));

Problem 2: Convert CSV to Grouped Object by Company

Your initial code is heading in the right direction—here’s a complete, robust implementation that handles edge cases and produces your expected output:

Complete Working Code

$(document).ready(function() {
  $.get('./software/software_standard.csv', function(data) {
    const lines = data.split('\n');
    const softwareObject = {};

    // Skip the header row (first line)
    for (let i = 1; i < lines.length; i++) {
      const line = lines[i].trim();
      // Skip empty lines to avoid errors
      if (!line) continue;

      // Split line into company and appID (trim values to remove extra whitespace)
      const [company, appID] = line.split(',').map(val => val.trim());

      // Initialize an array for the company if it doesn't exist yet
      if (!softwareObject[company]) {
        softwareObject[company] = [];
      }

      // Add appID to the company's array (remove the if check if duplicates are allowed)
      if (!softwareObject[company].includes(appID)) {
        softwareObject[company].push(appID);
      }
    }

    // Store the final object in localStorage as a JSON string
    localStorage.setItem('softwareData', JSON.stringify(softwareObject));

    // Verify the output in console
    console.log(softwareObject);
    // Expected output: {"Company A": ["1","2","3"], "Company B": ["2","3"]}
  });
});

Key Improvements:

  • Used $.get() instead of $(document).load() (since load() is designed for inserting HTML into elements, not fetching raw text data)
  • Added trimming for lines and values to avoid whitespace-related bugs
  • Handled empty lines to prevent invalid splits
  • Included a duplicate check for appIDs (remove this if duplicates should be preserved)
  • Properly initialized arrays for new companies before pushing appIDs

内容的提问来源于stack exchange,提问作者django_python_newbie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:33:52