NewOne
NewOne

Reputation: 401

How to correctly parse the JSON?

I have developed a Cordova android plugin for my library. The library is used for sending events across different connected devices.

JS interface receives a JSON from the java side. What I want to do is to parse this before reaching the application so that the developer can directly use it as a JS object. When I tried to parse the JSON in my plugin's JS interface, I am running into issues. Below is an example:

Received by JS interface:

{"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"}

After parsing in JS interface:

Object {key: "name", data: "{"name":"neil","age":2,"address":"2 Hill St"}"}
data:"{"name":"neil","age":2,"address":"2 Hill St"}"
key:"name"
__proto__:Object

As you can see, if this data reaches the app and the developer accesses the data:

eventData.key = name;
eventData.data = {"name":"neil","age":2,"address":"2 Hill St"};
eventData.data.name = undefined

How can I parse the inner data as well in my JS interface so that the developer can access directly. In the above case, he has to parse eventData.data to access the properties. I don't want this to happen and I want to do this in JS interface itself.

Please note that eventData can have many properties and hence they should be properly parsed before passing into the app.

I am new to Javascript and hence finding it difficult to understand the problem.

Upvotes: 0

Views: 423

Answers (2)

Patricia
Patricia

Reputation: 16

As others pointed out, you have to do JSON.parse(eventData.data) as the data comes as a string. You have to look why that happens. The inner data might be stored in this way, in some cases its valid to store it in db as flat object or it is stringified twice by mistake:

var innerdata = JSON.stringify({ name: "neil" });
var eventData = JSON.stringify({ key: "name", data: innerdata });

would correspond to your received string.

Correct way to stringify in first place would be:

var innerdata = { name: "neil" };
var eventData = JSON.stringify({ key: "name", data: innerdata });

Upvotes: 0

MFAL
MFAL

Reputation: 1110

It seems that your returned JSON contains a string for the data property.

    var response = {"key":"name","data":"{\"name\":\"neil\",\"age\":2,\"address\":\"2 Hill St\"}"};
    //Parse the data 
    var jsonData = JSON.parse(response.data);
    
    console.log(jsonData.name); //neil
    console.log(jsonData.age); //2
    console.log(jsonData.address);//"2 Hill St"

Upvotes: 1

Related Questions