Get comma separated string from array - javascript

I have the following JSON in JS.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":["num_domains", "med_load_time", "avg_load_time", "tot_req"]
}
I want the list of alerts to be removed and replaced with comma separated values as follows.
{
"url":"http://example.com/main.aspx",
"report_template_id":"1",
"interval_secs":"86400",
"analysis_type":"lite",
"email":"rokumar#example.com",
"alerts":"num_domains,med_load_time,avg_load_time,tot_req"
}

Just adding all the steps:-
1). Taking your JSON in a variable.
data = {"url":"http://example.com/main.aspx","report_template_id":"1","interval_secs":"86400","analysis_type":"lite","email":"rokumar#example.com","alerts":["num_domains","med_load_time","avg_load_time","tot_req"]};
2). Parse JSON data to object. Assuming the JSON is a string initially do a typeof(data) to be clear.
data = JSON.parse(data);
3) Change list of alerts to comma separated values
data.alerts = data.alerts.join(',');
4) Convert back to string
data = JSON.stringify(data)
So data will look like
{
"url": "http://example.com/main.aspx",
"report_template_id": "1",
"interval_secs": "86400",
"analysis_type": "lite",
"email": "rokumar#example.com",
"alerts": "num_domains,med_load_time,avg_load_time,tot_req"
}
Note:- If you will just say join() then also it will work, because default delimiter is , only, just to clarify I have given that.

Related

How to split into valid array

I've following object that is return from API and I want to convert them into array either in javascript or c#.
[
"1":"h1:first",
"2":".content a > img",
"3":"#content div p"
]
I've tried converting that to json object, split function etc but din't working for me.
It throws exception Uncaught SyntaxError: Unexpected token : while using split function in javascript.
You can convert it to valid JSON by replacing the square brackets with curly braces.
var data = '["1":"h1:first","2":".content a > img","3":"#content div p"]';
var json = `{ ${data.trim().slice(1, -1)} }`;
Then JSON.parse it like you had tried earlier. And if you want an array, and don't care about the actual index numbers, you can use Object.values to get the Array of values.
var data = '["1":"h1:first","2":".content a > img","3":"#content div p"]';
var json = `{ ${data.trim().slice(1, -1)} }`;
console.log(json);
var parsed = JSON.parse(json);
console.log(parsed);
var array = Object.values(parsed);
console.log(array);
I choose c# code to fix the issue instead client-side (as suggested by #rock star below).
string[] domSelectors = selectors.Replace("\"", "").Split(new string[] { "[", ",", "]" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var domSelector in domSelectors)
{
string[] arrayElements = domSelector.Split(':');
string selector = string.Join(":", arrayElements.Skip(1));
}
Hope it helps others who don't have control over API and want to fix the issue as I'd in my project!

Get first word of string inside array - from return REST

I try get the sessionid before REST function, but in the case if I does not convert toString(); show only numbers (21 22 2e ...).
See this image:
1º:
Obs.: Before using split.
!!xxxxxxx.xxxxx.xxxxxxx.rest.schema.xxxxResp {error: null, sessionID: qdaxxxxxxxxxxxxxj}
My code:
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxxxxx","password":"xxxxxxxx","platform":"xxxxx" },
headers: { "Content-Type": "application/json" }
};
client.registerMethod("postMethod", "xxxxxxxxxxx/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data); all return, image 1
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8'); // if i does not convert to string, return numbers, see image 1..
console.log(data); //all inside image 2, and i want just value from sessionid
var output = data;
var res = output.split(" "); // using split
res = res[4].split("}", 1);
}
console.log(res); //image 3
});
I tested with JSON.parse and JSON.stringify and it did not work, show just 'undefined' for all. After convert toString();, And since I've turned the values ​​into string, I thought of using split to get only the value of sessionid.
And when I used split, all transform to array and the return is from console.log(data), see image 2:
2º:
Obs.: After use split and convert to array automatically.
And the return after use split is with the conditions inside my code:
3º:
And the return after use split is with the conditions inside my code:
[ 'bkkRQxxxxxxxxxxxxx' ]
And I want just:
bkkRQxxxxxxxxxxxxx
I would like to know how to solve this after all these temptations, but if you have another way of getting the sessionid, I'd be happy to know.
Thanks advance!
After converting the Buffer to a string, remove anything attached to the front with using data.substr(data.indexOf('{')), then JSON.parse() the rest. Then you can just use the object to get the sessionID.
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
data = data.substr(data.indexOf('{'));
obj = JSON.parse(data);
console.log(obj.sessionID);
}
EDIT:
The issue you are having with JSON.parse() is because what is being returned is not actually JSON. The JSON spec requires the properties to be quoted ("). See this article
If the string looked like this, it would work: {"error": null, "sessionID": qdaxxxxxxxxxxxxxj}
Because the json is not really json, you can use a regular expression to get the info you want. This should get it for you.
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
console.log(match[2]);
EDIT 2: After fully reading the article that I linked above (oops haha), this is a more preferable way to deal with unquoted JSON.
var crappyJSON = '{ somePropertyWithoutQuotes: "theValue!" }';
var fixedJSON = crappyJSON.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
var aNiceObject = JSON.parse(fixedJSON);

set array as value in json format in Javascript

I want to add array as json value.
Json format is as follows.
json_data = [
'name':'Testing'
'email':'TestEmail'
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
]
How can I set value of 'links' in javascript like that?
I did as follows.
links_array = [];
links_array =['testing','test2'];
json_data.links = links_array;
I wanted to append these two string but couldn't.
Any help would be appreciate.
Assuming that the syntax of your example is correct, you can use the "push" method for arrays.
json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[]
};
json_data.links.push("test1#test.com");
json_data.links.push("test2#test.com");
json_data.links.push("test3#test.com");
You have to make little changes to make it work.
First thing, You have to replace initial square brackets with curly one. By doing this your object will become JSON Literal - a key value pair.
Second thing, You have missed commas after 'name':'Testing' and 'email':'TestEmail'
Below will work perfectly:
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com']
}
In addition to push as mentioned by #giovannilobitos you can use concat and do it all in one go.
var json_data = {
'name':'Testing',
'email':'TestEmail',
'links':[
'test#test.com',
'test#test1.com',
'test#test3.com'
]
};
var links_array = ['testing','test2'];
json_data.links = json_data.links.concat(links_array);
console.log(json_data.links);
On MDN's array reference you can find a more complete list of how to modify arrays in JavaScript.

JQuery unable to parse JSON string created by json_encode

I am currently in a bind, JQuery is unable to parse the following json strings
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
The above strings when parse through JSON.parse create the following arror:
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 112 of the JSON data
The PHP code which creates the string above is this:
public function getCustomerSuggestions($name){
$customers = $this->model->where('name','LIKE','%'.$name.'%')->show();
if(count($customers)>=1){
foreach($customers as $customer){
$list[] = ['value' => ucfirst($customer->name),'data' => $customer->id];
}
}
else{
$list[] = ['value' => 'No Customers Found', 'data'=> NULL];
}
$full_list['query'] = 'Unit';
$full_list['suggestions'] = $list;
return json_encode($full_list);
}
As you can see I am using the function json_encode to create the JSOn string so there should be no issue but it still doesnt work.
Edit
The json is sent using an autocomplete tool called DevBridge Autocomplete which takes the JSON strings and creates a suggestion list. The code I am using is
$('input[name=\"customer\"]').devbridgeAutocomplete({
serviceUrl: '".SITE_PATH."/ajax/admin/quotes/getcustomer',
minChars: 1,
onSearchStart: function (query){
var searchinput = $(this).val();
$('.autocomplete-suggestions').html('Searching: '+searchinput);
},
onSelect: function(suggestion){
var selection = $(this).val(suggestion.value);
$('input[name=\"customerid\"]').val(suggestion.data);
$.get('".SITE_PATH."/ajax/admin/quotes/getcustomerdetails',{id: suggestion.data},
function(response){
var obj = $.parseJSON(response);
$.each(obj, function(key, value){
$('#'+key).val(value);
});
});
}
});
It seems you have two JSON objects after each other. That's simply invalid. There can only be a single value at the root of a JSON "document". If you want to send down multiple objects, you need to put them in an array.
It seems getCustomerSuggestions is called multiple times and the return value of each call is returned to the client. Instead, the method should return an array, the caller should collect the return values in an array and JSON encode that array.
Well, your JSON string is NOT valid.
It should be,
[
{ "query":"Unit",
"suggestions":
[ {"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79} ] }
,
{"query":"Unit",
"suggestions":
[{"value":"Mr Ruto Kimutai ","data":88},{"value":"Mr Kimani Karanja","data":79}]}
]
But as Felix Kling said, check your PHP code.

Send JSON with unusual keys

I've object in js with keys-selectors:
{
"[data-index="0"]": {
// something
},
"> .class > .one": {
key: "very bad+ \"\' string"
}
}
How send this object via ajax without any changes in the keys and with correct values?
By correct values I mean that "very bad+ \"\' string" should be total escaped, but save all chars and signs to store in Database.
PS. I know that i can send objects via AJAX
JSON.stringify will transform your object into a JSON string. It can handle special characeters, don't worry.
var json = JSON.stringify(myObject);
When you modify your object a bit
var obj = {
"[data-index='0']": {
// something
},
"> .class > .one": {
key: "very bad+ \"\' string"
}
}
then a JSON.stringify(obj) works. The second pair of " after data-index= provokes an error.
-- edited syntax

Categories

Resources