osama
osama

Reputation: 116

How to process JSON coming from a android in nodejs

How to process JSON coming from a android in nodejs

I am building rest APIs in node using express. my API's are used by web client as well as from Android. From android data come in this form

"{\"info\":\"abc\"}" 

and from react app its come in this form

{ info:"abc"} 

so what is the solution of it i have search it but don't find any thing. and tell me what is the better way of exchanging data in rest API's.

what i have tried.

when i use JSON.parse it work fine with android but it through error

SyntaxError: Unexpected token o in JSON at position 1   

If i send data from react app using JSON.stringify it give this error

Cannot convert object to primitive value

Upvotes: 1

Views: 264

Answers (1)

Milan Velebit
Milan Velebit

Reputation: 2027

You're receiving a JSON string, just use JSON.parse(), like so:

const object = JSON.parse(your_JSON_string)

EDIT: since you've altered the question afterwards, if you're getting a

SyntaxError: Unexpected token o in JSON at position 1

it (probably) means that you've already got an object, no need to call JSON.parse() upon it.

Regarding the error that you're getting when you're trying to send data from the React app, you need to set the content-type header in your request to a proper content type.

My advice is to try and get a quick type check before you run any parsing on it, something along the lines of:

function getOrParseObject(your_received_object){
    if(typeof(your_received_object) === 'string') {
        // It's a string, should be parsed, so:
        return JSON.parse(your_received_object)
    } else if (typeof(your_received_object) === 'object'){
       // It's already an object, no need to parse it
       return your_received_object
    }
}

Upvotes: 2

Related Questions