当前位置: 首页 > 面试题库 >

如何将JSON转换为CSV格式并存储在变量中

吕高雅
2023-03-14
问题内容

我有一个在浏览器中打开JSON数据的链接,但是不幸的是我不知道如何读取它。是否可以使用JavaScript以CSV格式转换此数据并将其保存在JavaScript文件中?

数据如下:

{
  "count": 2,
  "items": [{
    "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
    "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China\u2019s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store\u2019s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
    "link": "http:\/\/wik.io\/info\/US\/309201303",
    "timestamp": 1326439500,
    "image": null,
    "embed": null,
    "language": null,
    "user": null,
    "user_image": null,
    "user_link": null,
    "user_id": null,
    "geo": null,
    "source": "wikio",
    "favicon": "http:\/\/wikio.com\/favicon.ico",
    "type": "blogs",
    "domain": "wik.io",
    "id": "2388575404943858468"
  }, {
    "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
    "description": "SHANGHAI \u2013 Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
    "link": "http:\/\/wik.io\/info\/US\/309198933",
    "timestamp": 1326439320,
    "image": null,
    "embed": null,
    "language": null,
    "user": null,
    "user_image": null,
    "user_link": null,
    "user_id": null,
    "geo": null,
    "source": "wikio",
    "favicon": "http:\/\/wikio.com\/favicon.ico",
    "type": "blogs",
    "domain": "wik.io",
    "id": "16209851193593872066"
  }]
}

我能找到的最接近的是:将MSExcel的JSON格式转换为CSV格式

但是它将下载到CSV文件中,我将其存储在一个变量中,即整个转换后的数据。

还想知道如何更改转义字符:'\u2019'恢复正常。

我尝试了这段代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>JSON to CSV</title>
  <script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    var json3 = {
      "count": 2,
      "items": [{
          "title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
          "description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
          "link": "http://wik.io/info/US/309201303",
          "timestamp": 1326439500,
          "image": null,
          "embed": null,
          "language": null,
          "user": null,
          "user_image": null,
          "user_link": null,
          "user_id": null,
          "geo": null,
          "source": "wikio",
          "favicon": "http://wikio.com/favicon.ico",
          "type": "blogs",
          "domain": "wik.io",
          "id": "2388575404943858468"
        },
        {
          "title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
          "description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
          "link": "http://wik.io/info/US/309198933",
          "timestamp": 1326439320,
          "image": null,
          "embed": null,
          "language": null,
          "user": null,
          "user_image": null,
          "user_link": null,
          "user_id": null,
          "geo": null,
          "source": "wikio",
          "favicon": "http://wikio.com/favicon.ico",
          "type": "blogs",
          "domain": "wik.io",
          "id": "16209851193593872066"
        }
      ]
    }
    //var objJson = JSON.parse(json3.items);

    DownloadJSON2CSV(json3.items);

    function DownloadJSON2CSV(objArray) {
      var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

      var str = '';

      for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
          line += array[i][index] + ',';
        }

        line.slice(0, line.Length - 1);

        str += line + '\r\n';
      }
      $('div').html(str);
    }
  </script>

</head>

<body>
  <div></div>
</body>

</html>

但这似乎不起作用。有人可以帮忙吗?


问题答案:

好的,我终于使这段代码起作用了:

<html>
<head>
    <title>Demo - Covnert JSON to CSV</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>

    <script type="text/javascript">
        // JSON to CSV Converter
        function ConvertToCSV(objArray) {
            var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
            var str = '';

            for (var i = 0; i < array.length; i++) {
                var line = '';
                for (var index in array[i]) {
                    if (line != '') line += ','

                    line += array[i][index];
                }

                str += line + '\r\n';
            }

            return str;
        }

        // Example
        $(document).ready(function () {

            // Create Object
            var items = [
                  { name: "Item 1", color: "Green", size: "X-Large" },
                  { name: "Item 2", color: "Green", size: "X-Large" },
                  { name: "Item 3", color: "Green", size: "X-Large" }];

            // Convert Object to JSON
            var jsonObject = JSON.stringify(items);

            // Display JSON
            $('#json').text(jsonObject);

            // Convert JSON to CSV & Display CSV
            $('#csv').text(ConvertToCSV(jsonObject));
        });
    </script>
</head>
<body>
    <h1>
        JSON</h1>
    <pre id="json"></pre>
    <h1>
        CSV</h1>
    <pre id="csv"></pre>
</body>
</html>

非常感谢您对所有贡献者的支持。



 类似资料:
  • 问题内容: 我尝试使用json格式的文件作为输入。这是示例数据的片段。 可以在r中使用这种复杂的json格式制作一个csv,以便更平滑地处理数据吗? 例如,有以下基本类别:基本信息照片创建者位置类别网址 可以制作带有basic_information.id,creator.id等子类别类别的csv文件吗? 问题答案: 在研究您的答案时,我在评论中张贴了一些链接,但现在我非常确信这是解决问题的方法。

  • 转换为json格式。

  • 问题内容: 我收到了JSON文件,但不知道如何读取。有转换器可以在其中生成漂亮的CSV文件,以便将其加载到MS Excel中吗?我不懂JSON,所以如果有人编写脚本或将我链接到可以完成此任务的脚本,那将非常棒。 我在http://json.bloople.net上找到了一些接近的东西,但是不幸的是,它是JSON到HTML。 编辑:jsonformat.com越来越近,但是它仍然不是CSV。 问题答

  • 问题内容: 以下是我的json文件输入 码 输出量 因此,在这里我确实得到了答案,但是没有打印一次,而是打印了7次。如何解决此问题。 问题答案: 是一个字典,您不需要对其进行迭代。您可以使用键直接访问值。 例如:

  • 问题内容: 我对编程非常陌生,过去3/4星期一直在学习python,这是给出的作业之一。 输入项 输出量 我一直在尝试代码为: 此代码的输出如下: 谁可以帮我这个事? 问题答案: 处理完整行后转储。

  • 问题内容: 我有一个要转换为CSV文件的JSON文件。如何使用Python执行此操作? 我试过了: 但是,它没有用。我正在使用Django,收到的错误是: 然后,我尝试了以下方法: 然后我得到错误: 样本json文件: 问题答案: 首先,你的JSON具有嵌套对象,因此通常无法直接将其转换为CSV。你需要将其更改为以下内容: 这是从中生成CSV的代码: 你将获得以下输出: