0

I have a Angular utility server and in that I have one method which I am using for searching some values in a JSON as below.

angular.module('myAppModule')
.service('myService', ['$rootScope', function($rootScope)
{
    this.myTestJson = '[{"id":1,"somthing":"somthing"},{"id":2,"somthing":"somthing"}]';

    this.getJsonObj = function(id)
    {
        if(id == null || id == undefined || id == "")
            return null;

        // Units Convert to JSON 
        var jsonObj = JSON.parse(JSON.stringify(this.myTestJson)); // How can I avoid this doing every time ?

        console.log("getJsonObj: jsonObj.length: "+jsonObj.length); //--> Printed invalid number, length of the string 
        for(var index=0;index < jsonObj.length;index++)
        {
            if( id == jsonObj[index].id )
                return jsonObj[index];
        }
        return null;
    };

}]);

Problem is I get JSON array length as invalid, and because of that I am not able to loop the array.

How can I access this JSON variable which is defined in the same service.

1
  • why your jason is in string and not just an normal array ? Commented Jun 29, 2016 at 15:36

1 Answer 1

2
this.myTestJson = '[{"id":1,"somthing":"somthing"},{"id":2,"somthing":"somthing"}]';

So, myTestJson is a String containing a JSON payload.

var jsonObj = JSON.parse(JSON.stringify(this.myTestJson));

And here, you're serializing this JSON string into JSON, only to reparse it right after. Which doesn't make any sense: you'll end up with the exact same string as the original one. Just like, if you transofmr an integer to a String, and then parse that String into an integer, you'll end up with the original integer.

To parse the original JSON and thus transform it to a JavaScript array, all you need is

var array = JSON.parse(this.myTestJson);

But even this is completely unnecessary, since you could just use a JavaScript array from the start, instead of parsing a JSON string:

var array = [
    {
        id: 1, 
        somthing:"somthing"
    },
    {
        id: 2,
        somthing: "somthing"
    }
];
Sign up to request clarification or add additional context in comments.

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.