Constructing a valid JSON object with Javascript - 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;
});

Related

How to write and read an array of objects to a file

I have this array of objects:
var people = {name:'list 1',mode:0,friends:[{user:1,code:'red'},{user:2,code:'blue'}]};
I want to write it to a file so if the node server crashes I dont lose the data. I did this:
//define variables from file
var file = "../../people.txt";
var open = fs.readFileSync(file);
va data = open.toString();
var name = data.name;
var mode = data.mode;
var friends = data.friends;
whenever a variable changes I save it to a file like this:
function update() {
//dosomething
name = 'new list';
mode = 1;
friends = [{user:4,code:'red'},{user:6,code:'blue'}]
fs.writeFileSync(file,`{name:'${name}',mode:${mode},friends:${friends}'}`,{encoding:'utf8',flag:'w'});
}
This is output onto the file
{name:'list 1',mode:0,friends:[object, object]}
and the data cant be read at all. What am I supposed to do here?
Thank you.
You should convert the JSON data into a string format using JSON.stringify() before writing it to a file, and when reading them out, you should parse the string into JSON using JSON.parse()
More details are here and how to read/write JSON files

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()...).

Json stringify then parse from URL

I seem to be having an issue in stringify'ing then pasing from a url object
I simply stringify my object and set the location (with angulars $location) like so
currentUrl = {"module1" : {"is" : true} }
$location.search(JSON.stringify(currentUrl));
So this parses to the url just fine, however when I try to grab it from the url i get this back
console.log($location.search());
---
Object {{"module1":{"is":true}}: true}
How do I parse this back into an object so I can use it? If I do
JSON.parse($location.search());
I get a syntax error. I maybe because of how search returns the object? I am a bit confused here, could use some help. Thanks!
So I put it in the url with
$location.search(JSON.stringify(currentUrl));
What are the steps I need to take to get it back into this form :
{"module1" : {"is" : true} }
Edit -
It just appears it's setting the json object as the key in the location like
{ "mystrigifiedobject": true }
Edit2 :
based off the first edit, I was able to solve it (assming it's set in the locations object key) like so :
currentUrl = $location.search();
currentUrl = JSON.parse(Object.keys(currentUrl));
console.log(currentUrl);
This just feels a little weird though, am I doing something wrong here?
$location.search() returns the parsed search items from the url path as an object. This means this kind of url:
?a=b&c=d
will result in this object:
{ a: 'b', c: 'd' }
When you call this function:
currentUrl = {"module1" : {"is" : true} }
$location.search(JSON.stringify(currentUrl));
your path will look like this:
?%7B%22module1%22:%7B%22is%22:true%7D%7D
and the parsed object returned from $location.search will look like this:
{{"module1":{"is":true}}: true}
not that this is an object with one entry and the key is your JSON
So what you need to do in order to get your object back is this:
var parsedObject = $location.search();
var yourObject = JSON.parse(Object.keys(parsedObject)[0]);
see this jsfiddle: http://jsfiddle.net/HB7LU/11633/
But please note: you should encode your string when putting it in a url:
$location.search(encodeURIComponent(JSON.stringify(currentUrl)));
$routeParams provides access to both routing template values and query string values (as a string).
function ctrl($routeParams) {
var yourValueAsString = $routeParams.yourKey;
}
function ctrl2($location) {
$location.search('yourKey', JSON.stringify(...));
}
A better alternative would be to switch to using the UI Router which deals with this better.

Categories

Resources