将数据从接收的JSON格式转换为JVectorMap格式 [英] Convert data from received JSON format to JVectorMap format
问题描述
我正在开发MVC 5中的MIS仪表板,在该仪表板中我想使用 JVectorMap 加载注册国家。以下是我的控制器操作返回JSON
public JsonResult registeredCountries()
{
var ret = db.View_RegisteredCountries.Select(x => new {Key = x.CountryCode,Value = x.TotalCompanies})。ToDictionary(x => x.Key,x => x.Value)。ToList();
返回Json(ret,JsonRequestBehavior.AllowGet);
}
以下是我获取JSON的JS代码
var data = {};
$ .ajax({
url:'registeredCountries',
类型:'GET',
传统:true,
async:false,
cache :false,
// async:false,
dataType:'json'
})。done(function(result){
data = result;
}) ;
但我的问题是JVectorMap使用以下格式的数组
data_array = {
US:4977,
AU:4873,
IN:3671,
BR:2476,
TR:1476,
CN:146,
CA:134,
BD:100
};
但返回的JSON格式如下
[{Key:SA,Value:4}]
如何将上述JSON转换为以下格式,以便可以填充JVectorMap。
data_array = {
SA:4
}
只需走一段输入并从每个条目创建一个对象。
//设置一些示例数据 - 在您的情况下,您已经拥有this.var数据= JSON.parse('[{Key:SA,Value:4},{Key:US,Value:12},{Key:BR,Value :6}]')var obj = {} //创建一个新对象来构建results.for(var i = 0; i< data.length; i = i + 1){obj [data [i]。 Key] = data [i] .Value} //注意jquery仅用于此调试输出。$(#output)。html(JSON.stringify(obj))
< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1。 1 / jquery.min.js>< / script>< div id =输出>< / DIV>
I am developing dashboard of a MIS in MVC 5, and in that dashboard I want to use JVectorMap to load the registered countries. So following is my controller action that returns the JSON
public JsonResult registeredCountries()
{
var ret = db.View_RegisteredCountries.Select(x => new { Key = x.CountryCode, Value = x.TotalCompanies }).ToDictionary(x => x.Key, x => x.Value).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
and following is my JS code to get the JSON
var data = {};
$.ajax({
url: 'registeredCountries',
type: 'GET',
traditional: true,
async: false,
cache: false,
//async: false,
dataType: 'json'
}).done(function(result) {
data = result;
});
But my problem is that JVectorMap use the array in the following format
data_array = {
"US": 4977,
"AU": 4873,
"IN": 3671,
"BR": 2476,
"TR": 1476,
"CN": 146,
"CA": 134,
"BD": 100
};
but the returned JSON is in the following format
[{ "Key": "SA", "Value": 4 }]
How do I convert the above JSON to the following format so that JVectorMap could be populated.
data_array = {
"SA":4
}
Simply a matter of walking the array of inputs and create an object from each entry.
// set up some sample data - in your case you already have this.
var data = JSON.parse('[{"Key":"SA","Value":4},{"Key":"US","Value":12},{"Key":"BR","Value":6}]')
var obj={} // make a new object to build results.
for (var i =0; i < data.length; i = i + 1) {
obj[data[i].Key] = data[i].Value
}
// Note jquery only used for this debug output.
$("#output").html(JSON.stringify(obj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>
这篇关于将数据从接收的JSON格式转换为JVectorMap格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!