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

2024-03-06

我有一个可以在浏览器中打开 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"
  }]
}

我能找到的最接近的是:将 JSON 格式转换为 MS Excel 的 CSV 格式 https://stackoverflow.com/questions/4130849/convert-json-format-to-csv-format-for-ms-excel

但它下载为 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>

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


将 json 转换为 csv 的一种更优雅的方法是使用不带任何框架的 map 函数:

var json = json3.items
var fields = Object.keys(json[0])
var replacer = function(key, value) { return value === null ? '' : value } 
var csv = json.map(function(row){
  return fields.map(function(fieldName){
    return JSON.stringify(row[fieldName], replacer)
  }).join(',')
})
csv.unshift(fields.join(',')) // add header column
 csv = csv.join('\r\n');
console.log(csv)

Output:

title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
"Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","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","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
"Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","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","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"

更新 ES6 (2016)

使用这种不太密集的语法以及 JSON.stringify 向字符串添加引号,同时保持数字不带引号:

const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
  header.join(','), // header row first
  ...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')

console.log(csv)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 JSON 转换为 CSV 格式并存储在变量中 的相关文章

  • 在节点环境中存根 jQuery.ajax (jQuery 2.x)

    我正在尝试运行一些需要存根的测试jQuery ajax 我正在使用 SinonJS 来做到这一点 它曾经与旧版本的 jQuery 1 x 一起工作得很好 var require jquery var sinon require sinon
  • 有没有办法动态更改 jqGrid 的单元格值?

    这个问题可能已经被问过很多次了 但我想知道是否可以动态更改 jqgrid 的单元格值 我基本上有一个网格 它通过 JSON 字符串加载数据 在特定列的某些行上 该值可能为 null 因此 预先知道哪个行 ID 是一个问题 然后能够将 nul
  • 有没有一种方法可以在没有输入的情况下发送表单值

    假设我有以下表格
  • 我可以在 GWT 中使用第三方 Javascript 库吗

    例如穆工具 用 js 编码对我来说很舒服 但显然不适合所有人 你当然可以 最好的事情就是给自己写一些好看的JavaScript 覆盖类型 http code google com webtoolkit doc latest DevGuide
  • 参考上一个问题:为什么 VBA 没有加载所有发票详细信息

    除了上一个问题之外 我们在销售发票上仍然存在相同的加载失败问题 下面的 VBA Json 仍然仅加载一行或第一个产品详细信息行 而不是与表中该销售发票合作的所有产品行详细信息 我们希望下面的 VBA 能够根据参数加载发票详细信息 例如 如果
  • 如何显示接下来的三个图像单击加载更多按钮

    我需要一个加载更多按钮来显示图像 页面加载时 我显示 3 个图像 单击 加载更多 按钮后 接下来的 3 个图像将显示在屏幕上 我尝试了下面的代码 但它不起作用 你能帮我解决这个问题吗 function item slice 0 2 show
  • AngularJS + jQuery 移动

    是否还有其他可能性来设计AngularJS以移动友好的方式应用程序CSS 我正在计划一个移动应用程序 并希望使用 AngularJS 进行逻辑和数据绑定 但我不想自己设计所有内容CSS The AngularJSFAQ说它使用jQuery
  • 可以禁用幻灯片的触摸模拟但不能禁用滚动条(危险的滑动器)吗?

    我的页面上有一个危险的滑动器 它成功地模拟了幻灯片和随附滚动条上的触摸事件 允许单击鼠标并移动以向左或向右滑动幻灯片 这很好 但我现在在滑动器内的幻灯片上调用了可拖动 这意味着我需要停止此触摸模拟 拖动幻灯片并同时移动它们会引起混乱 但仅限
  • Angular2:动态同步http请求

    Goal 发出一系列同步 http 请求并能够将它们作为一个可观察流进行订阅 示例 不工作 let query arr test1 test2 test3 function make request query arr if query a
  • 从链接打开本地文件夹

    如何通过单击任何链接打开本地文件夹视图 我尝试了很多选择 例如 a href Open folder a or a Open folder a or a Open folder a 解决方案 启动可下载链接 以下内容适用于所有浏览器 但一如
  • 如何从 CSS 选择器中提取类名?

    故事 我目前正在构建一个 ESLint 规则 以警告在 CSS 选择器定位器中使用引导布局导向和角度技术类 目前我在字符串方法中使用简单的子字符串 for var i 0 i lt prohibitedClasses length i if
  • 为什么 call 比 apply 快那么多?

    我想知道是否有人知道why call比apply 在 Chrome 中 速度大约快 4 倍 在 Firefox 中快 30 倍 我什至可以制作自定义原型 apply2 在大多数情况下 运行速度是apply 这个想法取自角度 Function
  • 从网页运行 ClickOnce 应用程序,无需用户操作

    我们有一个基于 Java 的 Web 应用程序以及用 C 编写的相同应用程序 如果 java 检查器发现客户端计算机上没有安装 Java 则应该运行该应用程序 这个想法是运行 C 单击一次 http en wikipedia org wik
  • Firebase + Node.js:错误:找不到 XMLHttpRequest 兼容性库

    Firebase Node js On iOS 安装的 Node js npm 安装 firebase save 节点测试 js 其中 test js 是一个非常简单的连接到 Firebase 的脚本 var firebase requir
  • javascript - 如何获取对象名称或关联数组索引名称?

    我有一个像这样的 JSON 对象 var list name1 element1 value1 name2 element1 value2 如何提取所有 nameX 字符串值 例如 假设我想将它们连接在一个字符串中输出 例如 name1 n
  • Elm:如何从 JSON API 解码数据

    我有这个数据使用http jsonapi org http jsonapi org format data type prospect id 1 attributes provider user id 1 provider facebook
  • Three.js点击单个粒子

    In this example http jsfiddle net agqq96bq 2 您可以看到 2 个可点击的粒子 但它们都受到点击的影响 另外 我只想检测粒子上的点击 而不将它们过滤出场景 像这儿 if intersects len
  • jQuery Mobile + Admob:轮换?

    我使用 jQuery Mobile 框架创建了一个移动应用程序 所有页面都在index php中加载 使用 div 在每个页面的页脚中 我添加了Admob代码 div div div
  • 如何在单元测试中使用 JSON 发送请求

    我的 Flask 应用程序中有在请求中使用 JSON 的代码 我可以像这样获取 JSON 对象 Request request get json 这一直工作得很好 但是我正在尝试使用 Python 的 unittest 模块创建单元测试 但
  • JavaScript 阶乘防止无穷大

    我一直在 JavaScript 中使用这个函数来计算阶乘数 var f function factorial n if n 0 n 1 return 1 if f n gt 0 return f n return f n factorial

随机推荐