2016-11-20 71 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>