2

I was wondering how I could convert something like:

$scope.foo = [
               {name: "foo1", information : "bar1" },
               {name: "foo2", information : "bar2" }
             ]

into a JSON string? I searched Stack Overflow earlier for this question and was advised to use angular.toJson(obj, pretty) which I also researched on their website, but I wasn't able to successfully do it.

4
  • 1
    Did you try JSON.stringify($scope.foo)? Commented Sep 30, 2015 at 20:41
  • JSON.stringify($scope.foo) may be? If you want to convert it to String? Commented Sep 30, 2015 at 20:42
  • 1
    angular.toJson($scope.foo, true) should work fine. What errors did you get? Also angular.toJson($scope.foo) would work since pretty is optional Commented Sep 30, 2015 at 20:49
  • What @charlietfl said. angular.toJson() has been in there for quite a while and the preferred method, as it strips any $$ prefixed properties, so the errors you're getting should expose where the issue lies. Commented Sep 30, 2015 at 21:06

1 Answer 1

1

I've written the following on chrome console:

var foo = [
      {name: "foo1", information : "bar1" },
      {name: "foo2", information : "bar2" }
]
JSON.stringify(foo);

the output was: "[{"name":"foo1","information":"bar1"},{"name":"foo2","information":"bar2"}]"

I believe that is what you want.

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

3 Comments

will include angular hashkeys if array was used in a repeater though, angular.toJson() strips them out
Stringify worked!!! Thank you guys for your help! I did try it earlier but I made a very basic error; I called Stringify before I declared the array in the javascript file (yeah yeah i know i'm dumb). Still, it turned out alright!
Testing again in the chrome console, neither worked well with ng-repeat. If you wanna render your list with ng-repeat convert your json array back to javascript array with JSON.parse(foo) for example.

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.