Accessing a javascript object - javascript

I have been working on this problem for quite a while now.
I am defining an array using the following:
let newJsonObject = {
"billing_name": document.getElementsByName("order[billing_name]")[0].value,
"email": document.getElementsByName("order[email]")[0].value,
};
I get the data from storage and keep it in a variable named parsedJson, then do the three following console.log operations:
console.log(parsedJson);
console.log(parsedJson.billing_name);
console.log(parsedJson["billing_name"]);
This first returns an object with the following:
parameters:
{"billing_name": "123", "email": "123"}
However, the following two things logged in the console are undefined.
I have also tried to create the object with the keys not having quotations, but I am still getting undefined
I don't understand why the log is returning null when the object is defined. Does anyone have any suggestions?
EDIT:
Here is how I am storing the data:
chrome.storage.sync.set({"parameters": JSON.stringify(newJsonObject)});
Here is how I am accessing it:
chrome.storage.sync.get("parameters", params => {
if(params === null){
//Nothing is even set, simply return
return;
}else{
//Actually data saved in params
let parsedJson = params;
console.log(parsedJson);
console.log(parsedJson.parameters.billing_name);
console.log(parsedJson["billing_name"]);
Here is a link to what is displayed in console

use JSON.parse converts your json string to object
try this
console.log(JSON.parse(parsedJson.parameters).billing_name);

Try this:
var test = JSON.parse(parsedJson.parameters);
console.log(test.billing_name);
this will work.

Related

How to get to request parameters in Postman?

I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?
The pm.request.url.query.all() array holds all query params as objects.
To get the parameters as a dictionary you can use:
var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});
I have been looking to access the request params for writing tests (in POSTMAN). I ended up parsing the request.url which is available in POSTMAN.
const paramsString = request.url.split('?')[1];
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
console.log(params); // this is object with request params as key value pairs
edit: Added Github Gist
If you want to extract the query string in URL encoded format without parsing it. Here is how to do it:
pm.request.url.getQueryString() // example output: foo=1&bar=2&baz=3
pm.request.url.query returns PropertyList of QueryParam objects. You can get one parameter pm.request.url.query.get() or all pm.request.url.query.all() for example. See PropertyList methods.
It's pretty simple - to access YOUR_PARAM value use
pm.request.url.query.toObject().YOUR_PARAM
Below one for postman 8.7 & up
var ref = pm.request.url.query.get('your-param-name');
I don't think there's any out of box property available in Postman request object for query parameter(s).
Currently four properties are associated with 'Request' object:
data {object} - this is a dictionary of form data for the request. (request.data[“key”]==”value”) headers {object} - this is a dictionary of headers for the request (request.headers[“key”]==”value”) method {string} - GET/POST/PUT etc.
url {string} - the url for the request.
Source: https://www.getpostman.com/docs/sandbox
Bit late to the party here, but I've been using the following to get an array of url query params, looping over them and building a key/value pair with those that are
// the message is made up of the order/filter etc params
// params need to be put into alphabetical order
var current_message = '';
var query_params = postman.__execution.request.url.query;
var struct_params = {};
// make a simple struct of key/value pairs
query_params.each(function(param){
// check if the key is not disabled
if( !param.disabled ) {
struct_params[ param.key ] = param.value;
}
});
so if my url is example.com then the array is empty and the structure has nothing, {}
if the url is example.com?foo=bar then the array contains
{
description: {},
disabled:false
key:"foo"
value:"bar"
}
and my structure ends up being { foo: 'bar' }
Toggling the checkbox next to the property updates the disabled property:
have a look in the console doing :
console.log(request);
it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)
Hope this helps
Alexandre
Older post, but I've gotten this to work:
For some reason the debugger sees pm.request.url.query as an array with the items you want, but as soon as you try to get an item from it, its always null. I.e. pm.request.url.query[0] (or .get(0)) will return null, despite the debugger showing it has something at 0.
I have no idea why, but for some reason, it is not at index 0, despite the debugger claiming it is. Instead, you need to filter the query first. Such as this:
var getParamFromQuery = function (key)
{
var x = pm.request.url.query;
var newArr = x.filter(function(item){
return item != null && item.key == key;
});
return newArr[0];
};
var getValueFromQuery = function (key)
{
return getParamFromQuery(key).value;
};
var paxid = getValueFromQuery("paxid");
getParamFromQuery returns the parameter with the fields for key, value and disabled. getValueFromQuery returns just the value.

Parsing a JSON object with Javascript, just won't work

I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Chrome Extension: StorageArea.Set key being passed as string

Good evening,
I'm trying to save an associative array into chrome.storage.local, like so:
var keyName = 'name';
var data = //grabbed from an Ajax call
saveData(keyName, data);
function saveData(keyName, data){
console.log("saving with key: "+keyName);
chrome.storage.local.set({keyName:data});
}
To check to make sure the data saved properly, I load:
function loadData(keyName){
console.log("loading: "+keyName);
chrome.storage.local.get(keyName, function(result){
console.log(result);
});
}
The log shows it is trying to load the correct key name, but nothing comes up. I then try calling loadData(null), which will show the entire contents of the local storage, and I find:
Object {keyName: Array[3]}
keyName: Array[3]
__proto__: Object
My data! But the key it saved with is "keyName" instead of "name". The log from saveData outputs that it is "saving with key 'name'", but it's saving with key "keyName" instead...
????
Thanks!
How strange...
Seems my question is similar to Using a variable key in chrome.storage.local.set
The answer they found was to convert the JSON {keyName:data} to an object:
var obj = {};
obj[keyName] = data;
chrome.storage.local.set(obj);
This works.
Is this because the JSON field is automatically passing as a string?

Constructing a valid JSON object with Javascript

I'm using the code below to construct a JSON object that looks like this:
{"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"myemail#hotmail.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_bxx.png"}]};
var data = {};
var contacts;
var gc = $.when(gigya.socialize.getContacts({callback: function(response){
data['contacts'] = response.contacts.asArray();
}}));
gc.done(function(response) {
contacts = data;
});
console.log(contacts);
When I pass the resulting contacts object to Google soy template, the JSON object doesn't seem well constructed.
With the code above, how do I construct a valid JSON object?
Thanks for helping out.
The object seems ok,
try using JOSN.stringify() example jsFiddle
or JSON.parse()
You can see in example, you can turn object into valid JSON and reverse into valid JS object.
Regarding your code
What do you get from response ?
And why do you use response here if you do not make use of it?
gc.done(function(response) {
contacts = data;
});
I would change this line EDITED
data['contacts'] = response.contacts.asArray();
to
contacts = JSON.parse(response.contacts);
and remove
gc.done(function(response) {
contacts = data;
});

Categories

Resources