简体   繁体   English

如何将json格式从对象转换为数组

[英]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.另一个问题:P,我正在尝试更改 JSON 数组的输出,但我无法弄清楚为什么它不会呈现其他文件。

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.抱歉,如果您查看我的要点中的代码,我不是很清楚, data[name] = { 会将所有返回名称呈现到单独的 json 文件中,但是如果我删除 [name] 并且它只是 data = { 个人文件不会被渲染,all.json 文件是由渲染的 [name] 文件组成的。 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.您给我的代码将“markets” [] 添加到 all.json 文件中,因为它应该但没有其他文件 all.json 只有一个返回。 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.我想从 data[name] = 中删除 [name] 的原因是它将名称添加到每个返回的字符串的开头,例如 { "Bitcoin": {"position": "1", "name" :"Bitcoin",},{"Litecoin": {"position":"2", "name": "Litecoin", },依此类推。

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.所以我想我想要做的是将 [name] 从 data[name] = 移动到 fs.writeFile 函数中,并且只添加“markets”:在字符串的开头并且仍然能够呈现单个文件进入 all.json。

The Node.js code that will not render the individual files.不会呈现单个文件的 Node.js 代码。

This versions all.json only returns此版本 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}

and in the json folder并在 json 文件夹中

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

What I would like is the JSON format to be:我想要的是 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([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此版本将呈现所有文件,但将 [name] 添加到 all.json

this version json folder这个版本的json文件夹

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

The JSON format is: 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([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尝试使用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>

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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