如何将json格式从Object转换为Array

时间:2015-06-27 14:39:21

标签: javascript arrays json node.js

另一个问题:P,我试图更改JSON数组的输出,但我无法解决为什么它不能渲染其他文件。

在下面编辑更好的解释。

抱歉,如果你看看我的要点中的代码,我不是很清楚,data [name] = {会将所有的返回名称渲染到单独的json文件中,但如果我删除[name]并且它只是数据= {不渲染单个文件,并且all.json文件来自渲染的[name]文件。 希望这能解释得更好一点。 您给我的代码剂量增加"市场" []应该是all.json文件,但没有其他文件all.json只有一个返回。 我想从数据[name] =中删除[name]的原因是它将名称添加到每个返回的字符串的开头,例如{"比特币":{" position&# 34;:" 1"," name":"比特币",},{" Litecoin":{" position&#34 ;:" 2"," name":" Litecoin",}等等。

所以我想我想要做的是从数据[name] =移动[name] 进入fs.writeFile函数,只在字符串的开头添加" markets":仍然可以将各个文件渲染到all.json中。

不会呈现单个文件的Node.js代码。

此版本all.json仅返回

{"position":"650","name":"Pennies","symbol":"CENT","icon":"pennies.png","market_cap":{"usd":"NaN","btc":"?"},"price":{"usd":"2.26018e-9","btc":"9.05947e-12"},"supply":"","volume":{"usd":"43.9142","btc":"0.176021"},"change1h":"0.05","change24h":"3.77","change1d":"-7.07","timestamp":1435559515.397}

并在json文件夹中

http://s21.postimg.org/xm7v01ujr/image.jpg

我想要的是JSON格式:

{
    "markets": [
        {
            "position": "1",
            "name": "Bitcoin",
            "symbol": "BTC",
            "icon": "bitcoin.png",
            "market_cap": {
                "usd": "3504403422",
                "btc": "14319000.0"
            },
            "price": {
                "usd": "244.738",
                "btc": "1.0"
            },
            "supply": "14319000",
            "volume": {
                "usd": "13563600",
                "btc": "55523.8"
            },
            "change1h": "0.26",
            "change24h": "1.05",
            "change1d": "1.21",
            "timestamp": 1435401749.236
        },
        {
            "position": "2",
            "name": "Litecoin",
            and so on.......
        }
    ]
}



#!/usr/bin/nodejs
var request = require("request"),
    cheerio = require("cheerio"),
    fs = require("fs");
 
var currencies = ["usd", "btc"];
var currencyExchangeRates = Array();
var data = {};
 
request('http://coinmarketcap.com/all/views/all/', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    $ = cheerio.load(body);
    currencyExchangeRates = $("#currency-exchange-rates").data();
    $("tr").each(function (i) {
    	if (i > 0) {
	var td = $(this).find("td");
        var position = td.eq(0).text().trim();
        var icon = $(this).find("img.currency-logo").attr("src").replace("/static/img/coins/16x16/", "");
	var name = td.eq(1).text().replace("/", "").trim();
        var re = /\s([a-z]|[0-9])+\s/i;
        var supplyText = td.eq(5).text();
        var symbol = td.eq(2).text().trim();
	var marketCap = currencyDictionary(td.eq(3));
        var price = currencyDictionary(td.eq(4).find("a").eq(0));
	var supply = td.eq(5).text().replace(/\D/g, "").trim(); // Replace all non digit characters with nothing
	var volume = currencyDictionary(td.eq(6).find("a").eq(0));
	var change1h = td.eq(7).text().replace("%", "").trim();
        var change24h = td.eq(8).text().replace("%", "").trim();
        var change1d = td.eq(9).text().replace("%", "").trim();
	var timestamp = Date.now() / 1000;
	data = [{
            "position": position,
            "name": name,
            "symbol": symbol,
            "icon": icon,
            "market_cap": marketCap,
            "price": price,
            "supply": supply,
            "volume": volume,
            "change1h": change1h,
            "change24h": change24h,
            "change1d": change1d,
            "timestamp": timestamp
        }];
      }
    });
    writeData();
  }
});
 
function currencyDictionary(item) {
  var resultArray = {};
  currencies.forEach(function(currency) {
    if (currency == "btc") {
      var result = item.data("btc");
    }
    else {
      var result = item.data("usd") / currencyExchangeRates[currency];
    }
    resultArray[currency] = result.toString().replace(/,/g,"");
  });
  return resultArray;
}
 
function writeData() {
    dataDir = "/var/www/coinmarketcap/json/";
    callback = function(error) {
	if (error) {
	    console.log(error);
	}
    };
    for (currency in data) {
    info = data[currency];
    fileName = dataDir + info["symbol"] + ".json";
    fs.writeFile(fileName, JSON.stringify(info), callback);
    }
    fs.writeFile(dataDir + "all.json", JSON.stringify(data), callback);
}




此版本将呈现所有文件,但将[name]添加到all.json

此版本的json文件夹

http://s16.postimg.org/xicupqi85/image.jpg

JSON格式为:

{
    "Bitcoin":
  {
    "position": "1",
    "name": "Bitcoin",
    "symbol": "BTC",
    "icon": "bitcoin.png",
    "market_cap": {
      "usd": "3504403422",
      "btc": "14319000.0"
    },
    "price": {
      "usd": "244.738",
      "btc": "1.0"
    },
    "supply": "14319000",
    "volume": {
      "usd": "13563600",
      "btc": "55523.8"
    },
    "change1h": "0.26",
    "change24h": "1.05",
    "change1d": "1.21",
    "timestamp": 1435401749.236
  },
{ 
    "Litecoin": 
  { 
    "position" "2",
    "name": "Bitcoin",
    and so on...
  }
}



#!/usr/bin/nodejs
var request = require("request"),
    cheerio = require("cheerio"),
    fs = require("fs");
 
var currencies = ["usd", "btc"];
var currencyExchangeRates = Array();
var data = {};
 
request('http://coinmarketcap.com/all/views/all/', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    $ = cheerio.load(body);
    currencyExchangeRates = $("#currency-exchange-rates").data();
    $("tr").each(function (i) {
    	if (i > 0) {
	var td = $(this).find("td");
        var position = td.eq(0).text().trim();
        var icon = $(this).find("img.currency-logo").attr("src").replace("/static/img/coins/16x16/", "");
	var name = td.eq(1).text().replace("/", "").trim();
        var re = /\s([a-z]|[0-9])+\s/i;
        var supplyText = td.eq(5).text();
        var symbol = td.eq(2).text().trim();
	var marketCap = currencyDictionary(td.eq(3));
        var price = currencyDictionary(td.eq(4).find("a").eq(0));
	var supply = td.eq(5).text().replace(/\D/g, "").trim(); // Replace all non digit characters with nothing
	var volume = currencyDictionary(td.eq(6).find("a").eq(0));
	var change1h = td.eq(7).text().replace("%", "").trim();
        var change24h = td.eq(8).text().replace("%", "").trim();
        var change1d = td.eq(9).text().replace("%", "").trim();
	var timestamp = Date.now() / 1000;
	data[name] = {
            "position": position,
            "name": name,
            "symbol": symbol,
            "icon": icon,
            "market_cap": marketCap,
            "price": price,
            "supply": supply,
            "volume": volume,
            "change1h": change1h,
            "change24h": change24h,
            "change1d": change1d,
            "timestamp": timestamp
        };
      }
    });
    writeData();
  }
});
 
function currencyDictionary(item) {
  var resultArray = {};
  currencies.forEach(function(currency) {
    if (currency == "btc") {
      var result = item.data("btc");
    }
    else {
      var result = item.data("usd") / currencyExchangeRates[currency];
    }
    resultArray[currency] = result.toString().replace(/,/g,"");
  });
  return resultArray;
}
 
function writeData() {
    dataDir = "/var/www/coinmarketcap/json/";
    callback = function(error) {
	if (error) {
	    console.log(error);
	}
    };
    for (currency in data) {
    info = data[currency];
    fileName = dataDir + info["symbol"] + ".json";
    fs.writeFile(fileName, JSON.stringify(info), callback);
    }
    fs.writeFile(dataDir + "all.json", JSON.stringify(data), callback);
}




2 个答案:

答案 0 :(得分:1)

尝试使用for...in循环



var data = {
    "Bitcoin":
  {
    "position": "1",
    "name": "Bitcoin",
    "symbol": "BTC",
    "icon": "bitcoin.png",
    "market_cap": {
      "usd": "3504403422",
      "btc": "14319000.0"
    },
    "price": {
      "usd": "244.738",
      "btc": "1.0"
    },
    "supply": "14319000",
    "volume": {
      "usd": "13563600",
      "btc": "55523.8"
    },
    "change1h": "0.26",
    "change24h": "1.05",
    "change1d": "1.21",
    "timestamp": 1435401749.236
  }
};

var res = {"markets":[]};

for (var prop in data) {
  res.markets.push(data[prop])
};

document.getElementsByTagName("pre")[0].textContent = JSON.stringify(res, null, 4);

<pre></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

解决了这个问题,不得不从writeData函数中移出fs.writeFile for all.json,并为all.json提供在writeData函数完成后调用的自己的函数。