admin管理员组

文章数量:1410689

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 e in variable size.

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 e in variable size.

Share Improve this question asked Sep 27, 2014 at 9:22 ninja.stopninja.stop 4301 gold badge10 silver badges25 bronze badges
Add a ment  | 

3 Answers 3

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

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/dndp2wwa/1/

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

本文标签: javascriptJSON Parse only objectStack Overflow