Split json to elements and return each element to json

I wanted to know how to split the json content as attached in image json sample , to smaller one, this means return individual json like the following as a result

{
"dlg-0093d9ca-b42d-4b3c-9a89-c872000915f6": [
        {
            "utteranceID": 0,
            "speaker": "agent",
            "source": "[F]text[/F]",
            "target": ""
        },
        {
            "utteranceID": 1,
            "speaker": "customer",
            "source": "Hi. I'm trying to buy movie tickets at the AMC Houston 8 in Houston, Texas.",
            "target": ""
        }
    
    ]
}

this is currently the piece of code I'm using

function modifyJson_test() {
  var file = DriveApp.getFileById("14VzHnGLGefuf8zYnw8HIZpPfEUv19bkX"); //the json is stored to a drive file
  var text = file.getBlob().getDataAsString();
  var json = JSON.parse(text);
  //Logger.log(json[0])
  for (key in json) {
    the_array = json[key];
    var newArr = [key , the_array];
    var newJson = JSON.stringify(newArr, key);
    Logger.log(newJson)
  }
}

The output is as below with this code:

{
    "dlg-0093d9ca-b42d-4b3c-9a89-c872000915f6", [
        {
            "utteranceID": 0,
            "speaker": "agent",
            "source": "[F]text[/F]",
            "target": ""
        },
        {
            "utteranceID": 1,
            "speaker": "customer",
            "source": "Hi. I'm trying to buy movie tickets at the AMC Houston 8 in Houston, Texas.",
            "target": ""
        }
    
    ]
}

Which is not the output that I want to have. Could you please help to achieve this?

Upvotes: 0

Views: 187

Answers (2)

Keilath
Keilath

Reputation: 456

This should do the trick, you extract the values in the right way, but then you pack them as an array instead of packing them as an object

function modifyJson_test() {
  var file = DriveApp.getFileById("14VzHnGLGefuf8zYnw8HIZpPfEUv19bkX"); 
  var text = file.getBlob().getDataAsString();
  var json = JSON.parse(text);
  //Logger.log(json[0])

  for (key in json) {
    the_array = json[key];
    var newArr = {[key]: the_array};
    var newJson = JSON.stringify(newArr, key);
    Logger.log(newJson)
  }

}

Upvotes: 2

Jacob
Jacob

Reputation: 1840

That for loop is adding an unnecessary level of complexity to this project, keys in JSON are unique and therefore no looping is required.

function modifyJson_test() {
  var file = DriveApp.getFileById("14VzHnGLGefuf8zYnw8HIZpPfEUv19bkX"); //the json is stored to a drive file
  var text = file.getBlob().getDataAsString();
  var json = JSON.parse(text);
  var newJson = JSON.stringify({[key]: json[key]})
  Logger.log(newJson)
}

Upvotes: 0

Related Questions