2016-11-20 67 views
1

改变以下格式JSON格式我想这个数据格式转换:如何使用JavaScript

"color;blue:36 ,red:27"

以下JSON格式:

{ 
    "Record": [ 
    { 
     "type": "color", 
     "data": "blue", 
     "total": "36" 
    }, 
    { 
     "type": "color", 
     "data": "red", 
     "total": "27" 
    } 
    ] 
} 
+0

是'颜色;蓝色:36,红色:27'真的是你想要的格式转换? –

+0

是的..我得到这种格式的数据,即时通讯寻找将其转换为上述格式.. –

+0

你有更多的数据? –

回答

1

很难理解给定输入确切的问题,但应该足够了:

var input = "color;blue:36 ,red:27"; 
 

 
    // Reassignment is bad, but will shorten the example 
 
    input = input.split(";"); 
 

 
    var attributeName = input[0]; 
 

 
    // No length validations, also bad 
 
    var attributes = input[1].split(","); 
 

 
    var results = {"Record": attributes.map(function(a) { 
 
     a = a.split(":"); 
 
     return {"type":attributeName, 
 
      "data":a[0].trim(), 
 
      "total": a[1].trim()} 
 
    })}; 
 

 
    console.log(results)

+0

啊你赢了比赛! :) –

+0

这工作得很好..谢谢! :) –

1

这个建议首先分割字符串用分号获得type和数据,用' ,'分隔。然后用冒号分隔datatotal

var data = 'color;blue:36 ,red:27', 
 
    parts = data.split(';'), 
 
    object = { 
 
     Record: parts[1].split(' ,').map(function (a) { 
 
      var p = a.split(':'); 
 
      return { type: parts[0], data: p[0], total: p[1] }; 
 
     }) 
 
    }; 
 

 
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

+0

你给了答案,我什至不明白问题 – Mahi

+0

这一个工作以及..谢谢! :) –

0

这里是我会做它

var dataFormat = "color;blue:36 ,red:27" 
 
var splitFormat = dataFormat.split(";"); 
 
var type = splitFormat[0]; 
 
var colors = splitFormat[1].split(","); 
 
var results = []; 
 
_.each(colors, function(color) { 
 
console.log(color) 
 
    var obj = { 
 
    "type": type, 
 
    "data": color.split(":")[0], 
 
    "total":color.split(":")[1] 
 
    } 
 
    results.push(obj); 
 
}); 
 
var final = { 
 
    "Result": results 
 
}; 
 
$("#result").html(JSON.stringify(final));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="result"></div>