最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change json data in Angularjs - Stack Overflow

programmeradmin2浏览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.

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.

Share Improve this question edited Jul 6, 2015 at 16:38 sam_k asked Jul 2, 2015 at 19:45 sam_ksam_k 6,02314 gold badges82 silver badges112 bronze badges 5
  • use JSON.parse() to create a javascript object. Then modify the object and use JSON.stringify() to put it back into a string. – Frank Bryce Commented Jul 2, 2015 at 19:52
  • @JohnCarpenter Json.stringify() will convert in string – sam_k Commented Jul 2, 2015 at 19:52
  • see my answer for what I meant :) – Frank Bryce 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.? – sam_k 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? – Frank Bryce Commented Jul 2, 2015 at 22:48
Add a ment  | 

2 Answers 2

Reset to default 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./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 remend 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.

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;
发布评论

评论列表(0)

  1. 暂无评论