简体   繁体   中英

How to convert json formatting from Object to Array

Another issue :P, I'm trying to change the output of the JSON array but I can't workout why it won't render the other files.

Edit better explanation below.

Sorry i was not very clear if you look at the code in my gist, data[name] = { will render all the return names into there individual json files, But if i remove the [name] and its just data = { the individual files are not rendered and the all.json file is made from the rendered [name] files. Hope this explains it a little better. The code you gave me dose add "markets" [] to the all.json file as it should but without the other files all.json only has one return. The reason why i want to remove [name] from the data[name] = is that it adds the name to the start of the string of every return eg { "Bitcoin": {"position": "1", "name":"Bitcoin",},{"Litecoin": {"position":"2", "name": "Litecoin", }, and so on.

So i guess what i am trying to do is move the [name] from the data[name] = into the fs.writeFile function and only add "markets": at the start of the string and still be able to render the individual files into all.json.

The Node.js code that will not render the individual files.

This versions all.json only returns

{"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}

and in the json folder

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

What I would like is the JSON format to be:

{
    "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([az]|[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); }

This version will render all the files but adds the [name] to the all.json

this version json folder

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

The JSON format is:

{
    "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([az]|[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); }

Try utilizing for...in loop

 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>

解决了,不得不将 all.json 的 fs.writeFile 移出 writeData 函数,并为 all.json 提供自己的函数,该函数在 writeData 函数完成后调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM