Unable to get the value from a JavaScript object - javascript

I have created a JSON object and put it under session object.
How can I retrieve the value from the JSON?
This is my program
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', datainsession);
var val_sess = window.sessionStorage.getItem(keyname);
var firstname = val_sess.firstName;
alert(firstname);
http://jsfiddle.net/5bea0mr2/3/
Could you please tell me how I can retrieve the first name?

Session storage can only hold strings, not objects. Your session here ends up holding your object converted to a string ("[Object object]"), and not the object itself.
To get around this we can firstly convert the object to a JSON string using JSON.stringify():
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
-> '{"firstName":"John","lastName":"Doe"}'
Then when pulling it convert it back to an object by using JSON.parse():
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
-> {"firstName":"John","lastName":"Doe"}

window.sessionStorage.setItem can only store serialised objects.
So you have to serialise it first via JSON.stringify:
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession))
Then to retrieve it via JSON.parse:
var val_sess = window.sessionStorage.getItem(keyname);
var obj = JSON.parse(val_sess);
// obj.firstName is what you need.

JSON is represented by a string, not an object. It's simply a JavaScript object with string keys. You'll need to use JSON.stringify() and JSON.parse() to convert the JavaScript object.
Try the following:
var datainsession = {
firstName: "John",
lastName: "Doe"
};
var keyname = 'test';
window.sessionStorage.setItem(keyname, JSON.stringify(datainsession));
var val_sess = JSON.parse(window.sessionStorage.getItem(keyname));
var firstname = val_sess.firstName;
alert(firstname);

You need to convert it to a string on setting, and parse it when you get it out. This method only stores a string, but JSON methods can get around that. Eg.
var datainsession = {"firstName":"John", "lastName":"Doe"};
var keyname = 'test';
window.sessionStorage.setItem(keyname + '', JSON.stringify(datainsession));
var val_sess = window.sessionStorage.getItem('test');
var obj = JSON.parse(val_sess).firstName;
alert(obj);

Related

How to pass variable to JSON without printing it as String

How to pass variable to JSON object and print it like JSON object?
I simply want to pass variable value in JSON and print it like JSON which can also be used in console.table(obj)
With Stringify:
var name = "someName";
const json = JSON.stringify('{"result":'+name+', "count":42}');
const obj = JSON.parse(json);
console.log(obj);
Without stringify
var name = "someName";
const json = '{"result":'+name+', "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Using \"variableName\" it gets value in \"...\" and not the variable value
var name = "someName";
const json = '{"result":\"name\", "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Solution:
var debugJSON = [];
var section_number = 1;
var i = 25;
var x = section_number-i;
tempJSON = {
"section" : section_number,
"index" : i,
"fieldname" : x,
"isValid" : "not required"
};
debugJSON.push(tempJSON);
console.log(debugJSON);
//console.table(debugJSON); //Problematic on Chrome Browser and Stack Overflow
JSON is a text representation of some data structure.
Unless you write a JSON encoder (and you don't), you don't have any reason to produce JSON manually. Attempting to generate JSON using string concatenation fails if the variable strings (name in this case) contain quotes or backslash. Escaping them could produce valid results but the code becomes bloated and difficult to read without any gain.
JavaScript provides the method JSON.stringify() to produce a JSON from any data and this is the best way to generate JSONs.
All you have to do is to build the data structure that you need to encode. In your example, the data structure is an object:
let name = "someName";
const original = {
result: name,
count: 42,
}
// encode
const json = JSON.stringify(original);
console.log(json);
// decode
data = JSON.parse(json);
console.log(data);
Running the code snippet here in page is not relevant because the output that it produces looks similar for both calls of console.log().
Run the code using Node.js or run it in the browser's console to see the values of json (it is a string) and data (it is an object).
A JSON is quite literally a JavaScript object, so you don't treat it as a string, you work with objects, which you can later stringify if need be.
In your case, you don't want to pass a variable in a string, you should pass it in an object like so:
// Declaration of name
let name = 'someName';
// Create object and store name
const json = {
result: name,
count: 42
};
// Log object as JSON and as string
console.log(json);
console.log(JSON.stringify(json));
The first log returns your object as exactly that, an object, the second log, converts it into a string to do so as you please with it!

Removing double-quotes around Keys in Array

my array has keys with double-quotes "" around them, how can I remove them?
I'm generating my object from input fields like this:
var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
var jsonStringObj = {
users: [JSON.stringify(obj)]
};
console.log(jsonStringObj)
Result is like this:
users: ["{"Firstname":"","Lastname":""}"] <<-- wrong
Expected array:
users: [{Firstname:"john",Lastname:"doe"}] <<-- I want this
I have tried the following unsuccessful attempts:
var string = JSON.stringify(array);
string.replace (/"/g,'');
When you write JSON.stringify to convert it in the string, it would add the double quotes to your keys.
You just have to write obj directly, it would behave as the normal object and not string.
So please update your code of lines with the below code. It should resolve your problem.
var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
var jsonStringObj = {users: [obj]};
console.log(jsonStringObj)
You can use JSON.parse(),this will change a json to object. here is the example:
var obj = JSON.parse(users)
if you want to change an object to string you use JSON.stringify(obj)
There is no need to stringify the object at all.
var obj = {};
obj.Firstname = "";
obj.Lastname = "";
var obj2 = {users: [obj]};
console.log(obj2);

How to access part of string contained in an object in Javascript

I have an object that looks like this
{'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' }
I want to access part of what's contained in it
For example, if it was a normal object I would've thought I could do
objectName.variable
or
objectName.["variable"]
First of all, You should parse json data.
var obj = JSON.parse('{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}');
console.log(obj.variable);
console.log(obj.text);
etc ...
Firstly, parse the JSON - then because the data is a key, use Object.keys, then get the variable property:
const obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
const { variable } = JSON.parse(Object.keys(obj)[0]);
console.log(variable);
var obj = {'{"variable":"2","text":"fdsfdsfds","hotdog":"yes"}': '' };
// get keys from obj
var keys = Obejct.keys(obj);
// loop keys array
keys.forEach((item) => {
// !!! parse String to JSON !!!
var parsedObj = JSON.parse(item);
console.log(parsedObj.variable);
})

Why I can't parse JSON in JavaScript?

JSON contains one object:
results[0] = { 'MAX(id)': 1 }
And this code doesn't work:
var text = results[0];
var obj = JSON.parse(text);
console.log(obj.MAX(id));
results[0] is already an object type
You can parse only from string to object like this:
JSON.parse('{ "MAX(id)": 1 }');
Your object is already a JSON. You don't need to parse it.
To access MAX(id) property, you can use [] notation as follows:
results[0] = { 'MAX(id)': 1 };
console.log(results[0]['MAX(id)']);
Your result[0] is a real javascript object. JSON.parse transforms text into objects, so you can't parse other objects with it.
var results = { 'MAX(id)': 1 };
//var text = results;
//var obj = JSON.parse(text);
alert(results['MAX(id)']);

Get link to nested object by string key

For example, I have an object:
var model = {user:{name: 'Mike', phones:{mobile: '00000'}}};
and a string key:
var string_key = 'user.phones.mobile';
I can parse it to get the array key:
var keys = string_key.split('.');
How can I can get link to object phones from model?
By doing this:
model[keys[0]][keys[1]][keys[2]];
This seems a bit strange though..

Categories