[英]how to change the below format to json format using javascript
I want to convert this data format: 我想转换这种数据格式:
"color;blue:36 ,red:27"
to the following JSON format: 转换为以下JSON格式:
{
"Record": [
{
"type": "color",
"data": "blue",
"total": "36"
},
{
"type": "color",
"data": "red",
"total": "27"
}
]
}
This proposal splits the string first by semicolon for getting the type
and the data, delimited by ' ,'
. 该建议首先用分号分隔字符串以获取type
和数据,并以' ,'
分隔。 Then split by colon for data
and total
. 然后按冒号拆分以获取data
和total
。
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; }
It's hard to understand the exact problem with the given input, but that should suffice: 很难理解给定输入的确切问题,但这应该足够了:
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)
Here is how I'd do it 这是我会做的
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.