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.

5
  • use JSON.parse() to create a javascript object. Then modify the object and use JSON.stringify() to put it back into a string. Commented Jul 2, 2015 at 19:52
  • @JohnCarpenter Json.stringify() will convert in string Commented Jul 2, 2015 at 19:52
  • see my answer for what I meant :) Commented Jul 2, 2015 at 20:37
  • Can you please check my updated Question with code, How can I do which way I am trying.? Commented Jul 2, 2015 at 20:52
  • It is unclear to me what your follow up question is. Can you be specific in what is confusing about my answer? Commented Jul 2, 2015 at 22:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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()
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.
I have edited my answer to address your question. Also note that 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.
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.
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.
|
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.