简体   繁体   中英

Rewrite structure of a JSON Object

I need to make a lot of JSON files for a project. This JSON comes from Google Spreadsheets. Using data-drive I get JSON that looks like this:

{
  "custom_id": 1,
  "another_thing": "pizza",
  "step_1_message": "msg",
  "step_1_hint": "hint",
  "step_1_intent": "intent",
  "step_2_message": "msg",
  "step_2_hint": "hint",
  "step_2_intent": "intent"
}

Now I want all the steps to from an object by itself. Like so:

{
  "custom_id": 1,
  "another_thing": "pizza",
  "steps": [
   {"step_id": 1, "message": "msg", hint: "hint", "intent": "intent"},
   {"step_id": 2, "message": "msg", hint: "hint", "intent": "intent"}
  ]
}

Here is working solution:

var input = {
  "custom_id": 1,
  "another_thing": "pizza",
  "step_1_message": "msg",
  "step_1_hint": "hint",
  "step_1_intent": "intent",
  "step_2_message": "msg",
  "step_2_hint": "hint",
  "step_2_intent": "intent"
};
var output = {
    steps: []
};
for (var key in input) {
    var m = key.match(/step_([0-9]+)_(\w+)/);
    if (m) {
        var num = m[1];
        var name = m[2];
        if (!output.steps[num-1]) {
            output.steps[num-1] = {
                step_id: num
            };
        }
        output.steps[num-1][name] = input[key];
    } else {
        output[key] = input[key];
    }
}

perlish.

try matching each key-value pair vs a regex to look for keys matching "step", than take this key-valuepairs and forEach match further for message, hint, etc. use these values as constructor-values for your Object to be. you will need a dynamic constructor in your objects class definition, if this jsons have different amounts of key-value pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM