如何将这个字符串转换为JSON对象?

时间:2022-11-24 22:14:07

I have the following string coming in from users and need to turn it into JSON.

我有以下来自用户的字符串,需要将其转换为JSON。

2r,5g|3b,2r,4y|3g

I would like to convert it to JSON with JavaScript. Here is what I would like the JSON to look like:

我想用JavaScript把它转换成JSON。下面是我想要的JSON:

rounds = { 
    "round" : {
        "interval" : {
            "time" : "2",
            "color" : "r"
        },
        "interval" : {
            "time" : "5",
            "color" : "g"
        }
    },
    "round" : {
        "interval" : {
            "time" : "3",
            "color" : "b"
        },
        "interval" : {
            "time" : "2",
            "color" : "r"
        },
        "interval" : {
            "time" : "4",
            "color" : "y"
        }
    },
    "round" : {
        "interval" : {
            "time" : "3",
            "color" : "g"
        }
    }
}

I'm not really sure where to start here so any help is appreciated!

我不太确定从哪里开始,所以非常感谢大家的帮助!

4 个解决方案

#1


2  

You can use this code:

您可以使用以下代码:

var strRounds = "2r,5g|3b,2r,4y|3g";
var roundsSplit = strRounds.split("|");

var rounds = {};

for (var i = 0; i < roundsSplit.length; i++){
    var intervalsSplit = roundsSplit[i].split(",");

    if (intervalsSplit.length > 0){
        rounds["round" + i] = {};
    }

    for (var j = 0; j < intervalsSplit.length; j++){
        rounds["round" + i]["interval" + j] = {
            "time": intervalsSplit[j][0],
            "color": intervalsSplit[j][1]
        };
    }
}

But I have to say, that JSON written by you is not valid because its' fields must have unique names. I've used names like round0, round1... and interval0 and so on.

但是我不得不说,由您编写的JSON是无效的,因为它的字段必须有唯一的名称。我用过像round0, round1……间隔等等。

#2


0  

Split the string on "|" to get a new round, and then split each substring on "," to get intervals for that round.

在“|”上分割字符串以获得新一轮,然后在“,”上分割每个子字符串以获得该轮的间隔。

So you easily create a javascript map, and then use a Map to JSON conversion to get the JSON needed.

因此,您可以轻松地创建一个javascript映射,然后使用映射到JSON转换来获得所需的JSON。

#3


0  

The format you give is not valid JSON, since you have multiple instances of the same key. The following is an attempt at something more sane, by using arrays instead of objects with multiple instances of the same key:

您提供的格式不是有效的JSON,因为您有多个相同键的实例。下面是一个更合理的尝试,使用数组而不是具有多个相同键实例的对象:

function userStringToJSON(userString) {
    var arrayOfRounds = userString.split("|").map(function (roundString) {
        return roundString.split(",").map(function (intervalString) {
            var time = parseInt(intervalString, 10) + "";
            var color = intervalString.substring(time.length);

            return { time: time, color: color };
        });
    });

    return JSON.stringify(arrayOfRounds);
}

Then userStringToJSON("2r,5g|3b,2r,4y|3g") gives the string:

然后userStringToJSON(“2r,5g|3b,2r,4y|3g”)给出字符串:

[[{"time":"2","color":"r"},{"time":"5","color":"g"}],[{"time":"3","color":"b"},{"time":"2","color":"r"},{"time":"4","color":"y"}],[{"time":"3","color":"g"}]]

which is equivalent to the JavaScript array of array of objects given by

哪个等价于JavaScript数组中对象的数组

[
    [
        { time: "2", color: "r" },
        { time: "5", color: "g" }
    ],
    [
        { time: "3", color: "b" },
        { time: "2", color: "r" },
        { time: "4", color: "y" }
    ],
    [
        { time: "3", color: "g" }
    ]
]

In older browsers you will need es5-shim for map, and json2.js for JSON.stringify.

在旧的浏览器中,您将需要es5-shim作为map和json2。js JSON.stringify。

#4


0  

I don't know how much this will help you, but it does exactly what you need:

我不知道这对你有多大帮助,但它确实能满足你的需要:

<script>
    var string = "2r,5g|3b,2r,4y|3g";
    var inSplit = string.split('|');

    var myJson = "rounds = { ";

    for (var one = 0; one < inSplit.length; one++){
        var inOne = inSplit[one].split(',');
        myJson = myJson + '\n    "round" : {';
        for (var rnd = 0; rnd < inOne.length; rnd++){
            val = inOne[rnd].split('');
            myJson = myJson + '\n        "interval" : {';
            myJson = myJson + '\n            "time" : "'+val[0]+'",';
            myJson = myJson + '\n            "color" : "'+val[1]+'"';
            myJson = myJson + '\n        }';
            if(inOne.length > (rnd+1)){
                myJson = myJson + ',';
            }
        }
        myJson = myJson + '\n    }';
        if(inSplit.length > (one+1)){
            myJson = myJson + ',';
        }
    }
    myJson = myJson + '\n}';
    document.write(myJson);
</script>

Look on jsfiddle

看jsfiddle

#1


2  

You can use this code:

您可以使用以下代码:

var strRounds = "2r,5g|3b,2r,4y|3g";
var roundsSplit = strRounds.split("|");

var rounds = {};

for (var i = 0; i < roundsSplit.length; i++){
    var intervalsSplit = roundsSplit[i].split(",");

    if (intervalsSplit.length > 0){
        rounds["round" + i] = {};
    }

    for (var j = 0; j < intervalsSplit.length; j++){
        rounds["round" + i]["interval" + j] = {
            "time": intervalsSplit[j][0],
            "color": intervalsSplit[j][1]
        };
    }
}

But I have to say, that JSON written by you is not valid because its' fields must have unique names. I've used names like round0, round1... and interval0 and so on.

但是我不得不说,由您编写的JSON是无效的,因为它的字段必须有唯一的名称。我用过像round0, round1……间隔等等。

#2


0  

Split the string on "|" to get a new round, and then split each substring on "," to get intervals for that round.

在“|”上分割字符串以获得新一轮,然后在“,”上分割每个子字符串以获得该轮的间隔。

So you easily create a javascript map, and then use a Map to JSON conversion to get the JSON needed.

因此,您可以轻松地创建一个javascript映射,然后使用映射到JSON转换来获得所需的JSON。

#3


0  

The format you give is not valid JSON, since you have multiple instances of the same key. The following is an attempt at something more sane, by using arrays instead of objects with multiple instances of the same key:

您提供的格式不是有效的JSON,因为您有多个相同键的实例。下面是一个更合理的尝试,使用数组而不是具有多个相同键实例的对象:

function userStringToJSON(userString) {
    var arrayOfRounds = userString.split("|").map(function (roundString) {
        return roundString.split(",").map(function (intervalString) {
            var time = parseInt(intervalString, 10) + "";
            var color = intervalString.substring(time.length);

            return { time: time, color: color };
        });
    });

    return JSON.stringify(arrayOfRounds);
}

Then userStringToJSON("2r,5g|3b,2r,4y|3g") gives the string:

然后userStringToJSON(“2r,5g|3b,2r,4y|3g”)给出字符串:

[[{"time":"2","color":"r"},{"time":"5","color":"g"}],[{"time":"3","color":"b"},{"time":"2","color":"r"},{"time":"4","color":"y"}],[{"time":"3","color":"g"}]]

which is equivalent to the JavaScript array of array of objects given by

哪个等价于JavaScript数组中对象的数组

[
    [
        { time: "2", color: "r" },
        { time: "5", color: "g" }
    ],
    [
        { time: "3", color: "b" },
        { time: "2", color: "r" },
        { time: "4", color: "y" }
    ],
    [
        { time: "3", color: "g" }
    ]
]

In older browsers you will need es5-shim for map, and json2.js for JSON.stringify.

在旧的浏览器中,您将需要es5-shim作为map和json2。js JSON.stringify。

#4


0  

I don't know how much this will help you, but it does exactly what you need:

我不知道这对你有多大帮助,但它确实能满足你的需要:

<script>
    var string = "2r,5g|3b,2r,4y|3g";
    var inSplit = string.split('|');

    var myJson = "rounds = { ";

    for (var one = 0; one < inSplit.length; one++){
        var inOne = inSplit[one].split(',');
        myJson = myJson + '\n    "round" : {';
        for (var rnd = 0; rnd < inOne.length; rnd++){
            val = inOne[rnd].split('');
            myJson = myJson + '\n        "interval" : {';
            myJson = myJson + '\n            "time" : "'+val[0]+'",';
            myJson = myJson + '\n            "color" : "'+val[1]+'"';
            myJson = myJson + '\n        }';
            if(inOne.length > (rnd+1)){
                myJson = myJson + ',';
            }
        }
        myJson = myJson + '\n    }';
        if(inSplit.length > (one+1)){
            myJson = myJson + ',';
        }
    }
    myJson = myJson + '\n}';
    document.write(myJson);
</script>

Look on jsfiddle

看jsfiddle