1

I have an object:

[{"Spalte":3}]

How can I get only 3 ?

I tried something like that:

    var s = JSON.stringify(data);  // [{"Spalte":3}] as String
    var d = parseInt(s); // typeof d = number, 

When I tried to alert(d) I receive NaN.

1
  • 8
    data[0].Spalte? Commented Sep 27, 2016 at 9:18

3 Answers 3

3

You probably meant to do

var d = JSON.parse(s)[0].Spalte;

s contains a serialization of an object as JSON. So we parse it with JSON.parse to get back the original object and then use standard javascript to extract the numeric field. Notice there is no need for parseInt.

Alternatively, you can stringify the numeric field by itself:

var data = [{"Spalte":3}];
var s = JSON.stringify(data[0].Spalte);
var d = JSON.parse(s);

or even:

var data = [{"Spalte":3}];
var s = data[0].Spalte + ""; // simply convert a number to string
var d = parseInt(s); // parse the string back to a number.
Sign up to request clarification or add additional context in comments.

2 Comments

There is absolutely no need to use any JSON.* methods or string parsing. As Maxx already commented, a very simple data[0].Spalte does the trick. Also, you probably meant JSON.parse(s) instead of JSON.parse('3')?
Question is about stingify data and parsing a number out of it, not about what others believe about others having mistakes in the question. The mistake is the beliefe that the parseInt parse the int out from a string. To believe JSON.stringify is JSON.parse is unbelieveblabb.
2
var data = [{
  "Spalte": 3,
  valueOf() {
    return Spalte;
  }
}];

console.log(+data[0]) // 3

https://javascript.info/object-toprimitive

Comments

0

The obvious answer is:

var data = [{"Spalte":3}]
console.log(data[0].Spalte); //output number

If it is a string as others has proposed:

var data = '[{"Spalte":3}]'

//replace non-digits with nothing
data = data.replace(/[^0-9]*/g, '');

console.log(data); //output string

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.