2

I am having a JSON response as

{ "-0.15323": "" }

How to Parse the -0.15323 part only? I mean say

var json = '{ "-0.15323": "" }'
var obj = JSON.parse(json);

Now

return obj;

should return me -0.15323 only. Slice is not a good option. Because the data may come in variable size.

3 Answers 3

5

That is a Javascript Object literal.

So you can use the Object.keys function, which is the simpler equivalent of doing a loop through all the enumerable properties with the for-in loop (like in Donal's example):

var ob = {
  "-0.15323": ""
};
alert(Object.keys(ob)[0])

or even the Object.getOwnPropertyNames function, which FYI gives access to both enumerable and non-enumerable properties. You can access your property with:

var ob = {
  "-0.15323": ""
};

alert(Object.getOwnPropertyNames(ob)[0])

Both are Ecmascript 5, and should be supported in all major browsers.

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

Comments

5

That json is an object, so you can do something like this:

var obj = { "-0.15323": "" };
var key;

for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key);
    }
}

Here is a working example: http://jsfiddle.net/dndp2wwa/1/

Comments

2
parseFloat(Object.keys({"-1.2345":""})[0])

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.