0

I have following data as a JSON in one variable which I am building in one controller. I can access this json data in other controller using factory/service. Now I want to modify this json data as like output json data.

Input Json

[  
   {  
      "text":"Identity",
      "checked":true,
      "timestamp":1435862483093
   },
   {  
      "text":"Calendar",
      "checked":true,
      "timestamp":1435862483443
   },
]

Output :

{  
   "myname":{  
      "Facebook":{  
         "trackdata":[  
            {  
               "text":"Identity",
               "checked":true,
               "timestamp":1435862483093
            },
            {  
               "text":"Calendar",
               "checked":true,
               "timestamp":1435862483443
            }
         ],
         "selecteddata":[  
            {  
               "text":"Identity",
               "checked":true,
               "timestamp":1435862483093
            },
            {  
               "text":"Calendar",
               "checked":true,
               "timestamp":1435862483443
            }
         ]
      }
   }
}

What am I am trying :

        var trackdata = JSON.stringify(DataService.getTrackedData());
        var selecteddata = JSON.stringify(DataService.getSelectedData());

        var userJson = {};
        userJson["trackdata"] = trackdata;
        userJson["selecteddata"] = selecteddata;
        userJson["Facebook"] = ???
        userJson["myname"] = ???

What Can I write in last lines. The reason I put like is this in future "myname" and "Facebook" will be as per user input.

Update : 2

 pmApp.controller('FooterController', function ($scope, $state, DataService) {

    $scope.infunc = function () {
        console.log("Username : " + DataService.username);
        console.log("Application Name : " + DataService.applicationName);

        var username = DataService.username;
        var applicationName = DataService.username;

        $scope.outputJson = {
            username: {
                applicationName: {
                    "trackdata": DataService.getTrackedData(),
                    "selecteddata": DataService.getSelectedData()
                }
            }
        }

        /* $scope.outputJson.myname.Facebook.trackdata = ;
         $scope.outputJson.myname.Facebook.selecteddata = DataService.getSelectedData();*/

        console.log(JSON.stringify($scope.outputJson));

    };

});

It gives me output like this :

 "username":{  
      "applicationName":{  
         "trackdata":[  

Instead of username and applicationName it should print actual value of those variable. Can you please tell me what I am doing wrong here.

Thanks in advance.

Any help would be appreciated.

sam_k
  • 5,983
  • 14
  • 76
  • 110

2 Answers2

4

OK, here's something simple that I came up with:

// parse input in order to modify it
var inputObj = JSON.parse(input);

// create a new object based on your data from your input
var outputObj = {
    'myname': {
        'Facebook': {
            'trackdata': inputObj,
            'selecteddata': inputObj
        }
    }
};

// create new JSON output
var output = JSON.stringify(outputObj);

var input = '[     {        "text":"Identity",      "checked":true,      "timestamp":1435862483093   },   {        "text":"Calendar",      "checked":true,      "timestamp":1435862483443   }]';

var inputObj = JSON.parse(input);

var outputObj = {
  'myname': {
    'Facebook': {
      'trackdata': inputObj,
      'selecteddata': inputObj
    }
  }
};
  
var output = JSON.stringify(outputObj);
  
$('#input').html(JSON.stringify(inputObj,null,2));
$('#output').html(JSON.stringify(outputObj,null,2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input: <pre id="input"></pre><br>
Output: <pre id="output"></pre>

EDIT:

I think the is some confusion as to what JSON.parse() and JSON.stringify(). JSON.parse() takes a json string as input and outputs a javascript object. JSON.stringify() takes as input a javascript object and outputs a string. In what you tried, you are assigning a string to a javascript object field, when you probably want to assign an object to the field instead. Does that help?

EDIT:

To finish your example listed in the question, do the following.

var trackdata = JSON.stringify(DataService.getTrackedData());
var selecteddata = JSON.stringify(DataService.getSelectedData());

var fieldName1 = "Facebook";
var fieldName2 = "myname";

var userJson = {};
userJson["trackdata"] = trackdata;
userJson["selecteddata"] = selecteddata;
var userJson2 = {};
userJson2[fieldName1] = userJson;
var userJson3 = {};
userJson3[fieldName2] = userJson2;

Note: I would not recommend doing it this way, as it uses more variables, is confusing, and isn't easy to maintain. Building the object from root to children is much easier than vice versa, which is what your template code was attempting to do.

Frank Bryce
  • 8,076
  • 4
  • 38
  • 56
  • if you run the code snippet, you should see that the above code works :). For your specific example, replace `inputObj` in my code with `DataService.getTrackedData()` – Frank Bryce Jul 02 '15 at 20:45
  • Thanks for your reply. Shall i replace variable name instead of 'myname' and 'Facebook' ? Actually that would be different in my case every time. I want to put those names from variables. – sam_k Jul 06 '15 at 14:59
  • 1
    I have edited my answer to address your question. Also note that https://jsfiddle.net/ is a good place to go and write javascript code :). There, you can test small pieces of code until you're satisfied before adding them in to your larger pieces of code. – Frank Bryce Jul 06 '15 at 15:57
  • Thanks for your reply again. Check my updated question (Update-2 part), Its not working as I want to make it work. I am following your pattern to design it. Check updated code please. – sam_k Jul 06 '15 at 16:38
  • your syntax in your update is different than what I put in my answer. You can index an object like this. `obj[fieldName] = "some value"` but you cannot create an object like this `obj = {fieldName: "some value"}` because in javascript it will assume that you wanted the field name to be `fieldName`. – Frank Bryce Jul 06 '15 at 16:42
  • See https://jsfiddle.net/aLq00cp3/1/ for something that I came up with that might work for you. – Frank Bryce Jul 06 '15 at 17:04
  • Thanks for your help. Its worked and can you please take a look on this question : http://stackoverflow.com/questions/31274743/angular-js-error-duplicates-in-a-repeater-are-not-allowed-track-by-index-does – sam_k Jul 07 '15 at 16:50
0

Here are my example code:

$scope.inputJson = [  
  {  
    "text":"Identity",
    "checked":true,
    "timestamp":1435862483093
  },
  {  
    "text":"Calendar",
    "checked":true,
    "timestamp":1435862483443
  }
]

$scope.outputJson = {
  "myname": {
    "Facebook":{  
      "trackdata": [],
      "selecteddata": []
    }
  }
}

$scope.outputJson.myname.Facebook.trackdata = $scope.inputJson;
$scope.outputJson.myname.Facebook.selecteddata = $scope.inputJson;
Johnny Ha
  • 633
  • 5
  • 21