Search code examples
javascriptjsonobjectstringify

Extracting data from JSON.stringify


The data I receive back from my JSON.stringify looks like this.

 {"action":"deleted","data":{"latitude":9,"longititude":8,"_type":"locationcurrent","id":49,"user":"7"}}

But I can not seem to get the data inside of the objects. Mainly I want the value for action, "deleted", and the values for my data, like id:"49". But im having problems using this equation to try and get the data out.

 function replacer(key, value) {
            if (typeof value === "string") {
                return value;
            }
            return undefined;
        }

        var jsonString = JSON.stringify(message, replacer);
        console.log(jsonString);

All I get back from this is,

 data:{}

Solution

  • Your problem is that the first value that is passed to the replacer is the object itself. You replace this object by undefined because it is not of the type string.

    You need it change it that way:

    function replacer(key, value) {
        if ( key === '' || typeof value === "string") {
            return value;
        }
        return undefined;
    }
    

    But as Phatjam98 said, it does not make much sense to filter out one value that way.