oshirowanen
oshirowanen

Reputation: 15965

Removing junk from JSON?

For IE7 and IE8, I am capturing some JSONp to use in my webpage. Below is an extract of the JSONP:

{
    class: "min-temp",
    span: {
        class: "units-values temperature-units-values",
        span: [
            {
                class: "units-value temperature-value temperature-value-unit-c",
                span: {
                    class: "unit",
                    content: "°C"
                },
                content: "11
              "
            },
            {
                class: "units-value temperature-value temperature-value-unit-f",
                span: {
                    class: "unit",
                    content: "°F"
                },
                content: "52
              "
            }
        ]
    }
},

If you look at the content: "11 and content: "52, you will see that there are a lot of extra characters after them. How do I remove those extra characters so I only end up with the number, i.e. 11 or 52.

At the moment, I am extracting those numbers as follows:

day.span[1].span.span[0].content gives me 11 and day.span[1].span.span[1].content gives me 52.

Upvotes: 0

Views: 515

Answers (3)

jbabey
jbabey

Reputation: 46657

Use a regular expression to trim anything that is not a number.

content = content.replace(/\D/g, '');

Upvotes: 0

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22481

If you only expect integer values there, just use parseInt. It will ignore whitespaces.

Upvotes: 4

pete
pete

Reputation: 25091

If they're always expected to be numeric, you could parseInt or parseFloat the content, or as @Pointy suggested, you could use $.trim().

Upvotes: 1

Related Questions