简体   繁体   中英

how to create a json object reading from another json file

I have a json like this

{
"returnCode" : "200",
"message"     : "",
"Payload":[
  {
   "id" : "A",
   "series" : "Q1",
   "value" : "100",
  },{
   "id" : "A",
   "series" : "Q2",
   "value" : "110",
  },{
   "id" : "B",
   "series" : "Q1",
   "value" : "130",
  },{
   "id" : "B",
   "series" : "Q2",
   "value" : "150",
  }
 ]
}

Which i am reading using

$.getJSON("file.json",function(data){
     $.each(data.Payload, function(i,v){

     }    
})

I can iterate also. but reading from the json i need to create another json object which will used is fusion charts. The json I need to create is like the screenshot i have given 在此处输入图片说明

Plz help me to create this dynamically..

Your code should be like Also your json is different that can not full fill chart all parameters. you have to include " seriesname " viz data value list.Here you have only single list with value.

var catagory = [];
var datasetData = [];

//set list
if (response.returnCode == 200) {
    if (response.Payload.length > 0) {
        $(respomse.Payload).each(function (i, item) {
            catagory.push({
                "label": item.series
            });

            datasetData.push({
                "value": item.value
            });
        });
    }
}

Your Json object should be

var obj = {
    type: 'mscolumn3dlinedy',
    renderAt: 'chart-container',
    width: '550',
    height: '350',
    dataFormat: 'json',
    dataSource: {
        "chart": {
            "caption": "Product-wise Quarterly Revenue vs. Profit %",
            "subCaption": "Harry's SuperMart - Last Year",
            "xAxisname": "Quarter",
            "pYAxisName": "Sales",
            "sYAxisName": "Profit %",
            "numberPrefix": "$",
            "sNumberSuffix": "%",
            "sYAxisMaxValue": "25",
            "paletteColors": "#0075c2,#1aaf5d,#f2c500",
            "bgColor": "#ffffff",                
            "showBorder": "0",
            "showCanvasBorder": "0",
            "usePlotGradientColor": "0",
            "plotBorderAlpha": "10",
            "legendBorderAlpha": "0",
            "legendBgAlpha": "0",
            "legendShadow": "0",
            "showHoverEffect":"1",
            "valueFontColor": "#ffffff",
            "rotateValues": "1",
            "placeValuesInside": "1",
            "divlineColor": "#999999",
            "divLineIsDashed": "1",
            "divLineDashLen": "1",
            "divLineGapLen": "1",
            "canvasBgColor": "#ffffff",
            "captionFontSize": "14",
            "subcaptionFontSize": "14",
            "subcaptionFontBold": "0"
        },
        "categories": [
            {
                "category": catagory
            }
        ],
        "dataset": [
            {
                "seriesname": "Food Products",
                "data": datasetData
            },
            {
                "seriesname": "Non-Food Products",
                "data": datasetData
            },
            {
                "seriesname": "Profit %",
                "renderAs": "line",
                "parentYAxis": "S",
                "showValues": "0",
                "data": datasetData
                ]
            }
        ]
    }
}

Apply object to bind chart

var revenueChart = new FusionCharts(obj);

Essentially, from my understanding, you are trying to format the results of getJSON call. The simplest way to do this would be to organize the Payload object in "file.json" the way you need it to be. However, if that's not possible, you have to remember you know the format and properties of the data object returned by getJSON . Just copy over the ones you need. This code would go instead of your callback function (data) .

$.getJSON("file.json",function(data){
    // This object will store our properly formatted data, if you need 
    // access to it outside of this function, declare it outside of the callback
    var formatted_data = {
        "categories" : [],
        "dataset": []
    };

    // Used for efficiency to check if for duplicates
    var foundCategories = [];
    var foundSeries = [];

    // Loop over the result
    $.each(data.Payload, function(index, value) {
        // If we have seen this id already, there's nothing more to do
        var id = value["id"];
        if (foundCategories.indexOf(id) === -1) {
            // We have not seen this id before, store it and keep track of it
            foundCategories.push(id);
            formatted_data["categories"].push({ "category": { "label": id } });
        }

        // Check if we have seen this id before
        var series = value["series"];
        var indexOfSeries = foundSeries.indexOf(series);
        if (indexOfSeries === -1) {
            // We have not seen this series before, store it and keep track of it
            foundSeries.push(series);
            formatted_data["dataset"].push({
                "seriesname": series,
                "data": [{ "value": value["value"] }]
            });
        } else {
            // Add the data to the correct existing series
            formatted_data["dataset"][indexOfSeries]["data"].push({ "value":    value["value"] });
        }
    });  
});

Once again, it would be much easier if you could get your server to format the JSON for you, so you have to do minimal work on the frontend.

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