JavaScript object shows as a string instead of an item - javascript

So i am trying to display a data from an API using JavaScript but got an undefined instead when i console.log(data) what i am getting is like below. its an object but some how its encapsulate as a string? Any idea how to covert this into a actual object i am new with JavaScript api so i am a bit confused.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
I already tried to de serialize the data using JSON.parse(data) but no luck.

What you have posted is actually an object with a property msg which is a strigified JSON. In order to get proper json from this try obj.msg = JSON.parse(obj.msg); Assuming obj is the response variable you can name it what you want.
See below snippet.
{"msg":"{\"part\":\"test\",\"station\":\"test2\"}"}
const obj = {"msg":"{\"part\":\"test\",\"station\":\"test2\"}"} ;
console.log('Before parsing:' + typeof obj.msg); // string
obj.msg = JSON.parse(obj.msg);
console.log('After Parsing:' + typeof obj.msg); // object
Hope this helps :)

JSON.parse transforms a string-like-object to the object. So, it expects the whole of the object as a string. Which is not happening in your case.
You have an object key msg and its value is a string-like-object. So You need to convert the msg value to the JSON.
a couple of ways to try -
let resp = JSON.parse(data.msg)
or
return JSON.parse(data.msg)

Related

How to parsing the correct values from a json decoding [duplicate]

This question already has an answer here:
PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()
(1 answer)
Closed 1 year ago.
Hii ha ve written this question because i have a json converted to a string with a function of php called json_encode()
Something like this:
{ "data":"2","state":"false"}
when the original json that im trying to encode is like this:
{ "data":2,"state":false}
(Please note that the type of the variables are different, in the original i have an int number called data and boolean called state, but when i use json_encode() every variable goes to a string..)
The problem is when i try to json.PARSE() the value from the json encode of php in angular i donĀ“t get the correct value, every variable is a string...
For example, isntead of getting the boolean state of the variable, i get "false" or "true", and this is a problem...
There is a way to parse this avoiding this problem? basically my problem is when i parse the json in my angular project i dont get the correct type of variable..
Thanks!
You can use JSON.parse on an individual value to convert it into the desired type:
const oldValue = JSON.parse('{"data":"2","state":"false"}')
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = JSON.parse(oldValue[key]);
});
Here's the other way around:
const oldValue = JSON.parse('{"data": 2,"state": false}');
const result = {}
Object.keys(oldValue).forEach(key => {
result[key] = oldValue[key].toString();
});
Note: These examples assume flat objects. You'd need to recurse through the object's tree if some of the values are objects, for example {a: {b: "c"}}.

Access specific part of JSON JS

I am trying to access the t part of the "data": object below. I am doing this by doing console.log(message.data.f) however this returns undefined. I do not understand why I cannot access it in this way. See object below:
"data":"{\"e\":\"53845\",\"f\":\"SCORE\",\"pf\":[{\"p\":\"HOME\",\"v\":\"0\"},{\"p\":\"AWAY\",\"v\":\"0\"}],\"^t\":\"f\",\"i\":\"357575\",\"z\":1492771602631}",
Note I have marked the part of the object I wish to access with a ^
Your data property is a JSON string and probably all the object is a JSON string.
You need to parse the string as JSON
var obj = JSON.parse(myObj.data);
and then you can access:
console.log(obj.f);
If your first object, the one containing data, is not already a JSON too and its name is for example myFirstObject you need to do just this:
var jsonObj = JSON.parse(myFirstObject);
console.log(jsonObj.f);
Your message is nothing but string. Parse it first to a corresponding object to access its variables.
var parsed = JSON.parse(message);
console.log(message.data.t);

How does JSON.parse() work?

I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.

checking json value in javascript

var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);

Javascript JSON.parse or directly access

When we can read a property directly from string:
var data = {"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}};
console.log(data.address.streetName); // cde
Why do people use JSON.parse:
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
It is not a string, but Javascript object. String is given below
var data = '{"id":1,"name":"abc","address":{"streetName":"cde","streetId":2}}';
to make it object we use JSON.parse
var obj = JSON.parse(data);
console.log(obj.address.streetName); // cde
In your first example, data is an object, but in your second example, data is a JSON string.
That's a major difference. You could call eval(data) to parse a JSON string, but that's very unsafe.
JSON.parse() expects a string. More specifically, a string with a JSON-encoded piece of data.
If it's applied to an object then it's an error, the source of which is probably the common confusion that seems to exist between JavaScript objects and the JSON format.

Categories

Resources