将javascript数据转换为json文件

时间:2017-07-29 17:12:47

标签: javascript json

我正在使用TradingView小部件来绘制图表,数据以这种格式编码:

symbols: {          
  Equities: ['H&P', 'Google'], 
 }, 
 symbols_description: { 
    'H&P': ' BATS:HP ', 
    'Google': 'BATS:GOOG',      
}

我想使用json将符号和符号描述转换为动态代码。我正在努力如何使用json文件而不是硬编码。提前致谢。整个小部件代码是:

new TradingView.MiniWidget({
    container_id: 'tv-miniwidget-2', tabs: ['Equities'], 
    symbols: {          
       Equities: ['H&P', 'Google'], 
    }, 
    symbols_description: {
       'H&P': ' BATS:HP ', 
       'Google': 'BATS:GOOG',
    }, 
    width: 240, 
    large_chart_url: 'http://www.futuresmag.com/page/interactive-charts',
    gridLineColor: "#e9e9ea",
    fontColor: "#83888D",
    underLineColor: "#dbeffb",
    trendLineColor: "#4bafe9",                 
    height: 400,
    locale: "en"
    });

2 个答案:

答案 0 :(得分:0)

按步骤构建数据,而不是一次性构建数据

let options = {
  container_id: 'tv-miniwidget-2', tabs: ['Equities'],  
  width: 240, 
  large_chart_url: 'http://www.futuresmag.com/page/interactive-charts',
  gridLineColor: "#e9e9ea",
  fontColor: "#83888D",
  underLineColor: "#dbeffb",
  trendLineColor: "#4bafe9",                 
  height: 400,
  locale: "en"
}
// data format
let jsonData = {
  symbols: {          
    Equities: ['H&P', 'Google'], 
  },
  symbols_description: { 
    'H&P': ' BATS:HP ', 
    'Google': 'BATS:GOOG',      
  }
} // get data from server through ajax request or whatever you need
options.symbols = jsonData.symbols
options.symbols_description = jsonData.symbols_description

new TradingView.MiniWidget(options)

答案 1 :(得分:0)

要在浏览器中加载json文件,通常需要执行以下步骤:

  1. 对您的json文件进行Ajax调用
  2. 收到json文件后解析
  3. 解析后对文件内容执行某些操作
  4. 以下是一些演示代码,说明如何在不使用任何库的情况下执行此操作:

    var getJSON = function(url, successHandler, errorHandler) {
        // 1. Make an Ajax call to your json file
        var xhr = new XMLHttpRequest();
        xhr.open('get', url, true);
        xhr.onreadystatechange = function() {
            var status, data;
            if (xhr.readyState == 4) {
                status = xhr.status;
                if (status == 200) {
                    // 2. Parse the json file once it's been received
                    data = JSON.parse(xhr.responseText);
                    successHandler && successHandler(data);
                } else {
                    errorHandler && errorHandler(status);
                }
            }
        };
        xhr.send();
    };
    
    getJSON('widgetdata.json', function(data) {
        // 3. Do something with the content of the file once it's parsed
        var tradingView = new TradingView.MiniWidget(data);
    }, function(status) {
        // Error handling goes here
    });