How to change format of data in Javascript? - javascript

I am working with some integrations. I get data in Javascript file and I need to change the format slightly.
The data is received by Javascript in the following format:
["{label=Created By ID, value=Contact_ID__r.CreatedById}",
"{label=Created Date, value=Contact_ID__r.CreatedDate}",
...]
I need to convert the data in the following format in order to pass it ahead:
[{"label":"Start Date","value":"Contract_Start_Date__c"},
{"label":"Created Date", "value":"Contact_ID__r.CreatedDate"},
...]
I tried using JSON.stringify() and .replace() in various combinations to change the format. Eg: data[i].replace(/"/g, ''). Nothing worked. I am not able to change the format.
Please help. Thank You!
More Info:
The data is received from apex(just like java) in the form of Map<Map<String,String>,String>.
Eg:["{label=Created By ID, value=Contact_ID__r.CreatedById}","account"}]
In javascript, I extracted Map<String,String> part of it as follows:
//result.data contains the data returned by apex method.
//Variable availableOptionsForAccountFields will be used to display the data.
var iterator = 0;
var keys = Object.keys(result.data); //store the keys.
Object.keys(result.data).forEach(fieldToBeAddedAsAvailableOption => { //loop over the returned data.
//Identify the object of the field and add it to respective variable so that it can be displayed to the user
if (result.data[keys[iterator]] == 'account') {
this.availableOptionsForAccountFields.push(fieldToBeAddedAsAvailableOption);
}
iterator = iterator+1;
});
//After execution of this loop, the variable availableOptionsForAccountFields will have all the values to be displayed in dual listbox.
After extracting the data, I am left with the following data:
["{label=Created By ID, value=Contact_ID__r.CreatedById}"]
I need to convert this data into the following format so that I can display it using HTML:
[{"label":"Start Date", "value":"Contract_Start_Date__c"}]

Related

How to pass a Json array to JPQL Where clause for IN operator?

I've a multiple drop down select box available to select the list of genres. I'm creating a JSON array in JavaScript with all the genres selected by user & passing them to the back end Java function for plotting graph.
Database : MySQL
JavaScript:
var items = {};
$(function() {
$('#genres1').change(function() {
console.log($(this).val());
items.genres = $(this).val();
}).multipleSelect({
width: '56%'
});
});
var genres = items.genres.map(function(e){
return JSON.stringify(e);
});
var selectedGenres = genres.join(", ");
alert(selectedGenres); // Outputs : "Action", "Horror" and so on.... based on selection
Java:
public static void myFun(String genre){
Logger.info("Genre"+genre); //prints "Action","Horror"
List<String> selectedGenres = Arrays.asList(genre);
//List<String> selectedGenres = Arrays.asList("Action","Horror"); //Correct output
Logger.info("Genre"+selectedGenres); //prints ["Action","Horror"]
String queryString="SELECT wD FROM sed WHERE genre IN (:genres)";
Query query1=JPA.em().createNativeQuery(queryString).setParameter("genres", selectedGenres);
}
I'm not knowing how the array has to be passed to the query.
//List<String> selectedGenres = Arrays.asList("Action","Horror"); //Correct output
This hardcoded value gives me the correct output. When I pass the "selectedGenres" array containing exactly the same as above input - "Action","Horror"I don't get the preferred output. I also tried to send "genre" as it is as a parameter but it did not work though. I'm getting empty response. Can someone correct me where I'm going wrong?
List<String> selectedGenres = Arrays.asList(genre);
Some API clarification: Arrays#asList accepts String... vargs, where every argument is an element value to create the actual List.
Back to your method: your input argument is String genre (a String) while #asList method is not aware that this genre string is actually an array (and should not), and it does its job correctly - upon receiving a single element (a String in our case), a single-dimensional List is created.
To solve the issue, you may want to try one of those options:
(if your string is JSON array) Use JSON parsing library (such as Jackson)
Try to split the input (genre) by a comma, and transform that array back to List.

Best way to convert JSON data and implement values in checkbox,text,drop down or radio input type?

I'm trying to find the most efficient and generic solution for my single page app. There is 5 different tabs. Each tab is loading data in JSON object. Once user clicks on the tab JSON data is populated in the object with unique key. If user clicks on the Edit button I'm looping through JSON data and populating form fields. Here is my problem I have checkbox, radio, text and drop down menu fields on my form. Each data type requires different data type. My data in JSON object is not converted for checkbox or radio type input fields. I'm wondering what is the best way to approach this problem?
Here is example of my JSON data:
var jsonData = {
"frmTab1":{"st_fname":"mike","st_lname":"cook","st_iseligible":"yes"},
"frmTab2":{"sa_condition":"yes","sa_evaluation":"no"},
"frmTab3":{"se_respons":"yes","se_option":"3"},
... and so on
}
Here is my JQuery function that populates the form:
$('input[name="hmButton"]').on('click', function formSubmit(){
var btnVal = $(this).val();
if(btnVal == 'Edit'){
var jsonKey = $(this).attr('data-json'); //In data json is from id value
if($.isEmptyObject(jsonData[jsonKey])){
console.log('no data');
}else{
$.each(jsonData[jsonKey], function(index, element) {
//Here I need to check the input type and set checked if type is checkbox, or value if it's radio type, and same thing for drop down.
$('#frm' + index).val(element);
});
}
}
});
I was wondering if this could be done with another JSON object that will have key for each field with input type that is not equal text. If anyone can help please let me know. I'm trying to make this dynamic. This might be use in some other situation in my app. Thank you.
This...
var jsonData = {
'frmTab1': {
'st_fname': 'mike',
'st_lname': 'cook',
'st_iseligible': 'yes'
},
'frmTab2': {
'sa_condition': 'yes',
'sa_evaluation': 'no'
},
'frmTab3': {
'se_respons': 'yes',
'se_option': '3'
}
}
... is a JavaScript Object. JSON is a text-based data-interchange format, and although it's written in JavaScript Object Notation (hence JSON) try to avoid confusing JavaScript Objects with JSON data. Now that's out of the way... :)
Although JSON keys have to be defined between quotes ("...") as long as the keys in a JavaScript Object obey the usual syntax requirements the quotes for keys can be dispensed with...
var jsonData = {
frmTab1: {
st_fname: 'mike',
st_lname: 'cook',
st_iseligible: 'yes'
},
frmTab2: {
sa_condition: 'yes',
sa_evaluation: 'no'
},
frmTab3: {
se_respons: 'yes',
se_option: '3'
}
};
Your suggestion of referencing another Object which acts as an intermediary between the function which populates your page and the information in the jsonData variable is workable - perhaps something like this...
var dataMap = {
waypoint_1: jsonData.frmTab1,
waypoint_2: jsonData.frmTab2,
waypoint_3: jsonData.frmTab3
/* ... etc ... */
};
What I have called 'waypoint_n' here would reflect the properties/strings you're expecting to retrieve from your page element attributes - so that Something like...
var dKey = /* attribute value or property (String) */
var data = dataMap[ dKey ];
...would then place the required information from the jsonData Object in the data variable.
However, as you already have this information in an Object (jsonData) why not simply amend its keys to reflect the attribute values you're expecting?
You may find these links useful:
Eloquent JavaScript: The Secret Life of Objects
Eloquent JavaScript: Data Structures: Objects and Arrays
MDN: Working with JSON data

JSON decode list of lists in Django Python

I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.

What String format is acceptable to append to this JSON output?

I have an existing "blackbox" web service. I need to append a session ID to the end of that output so that Javascript and similar clients can resume the stateful session.
Given the output below, what is the correct syntax to append or prepend an arbitrary GUID, so that it can be properly deserialized as valid JSON?
Note This data below is perfect. If I can somehow add a "removable" bit of information, using JSON.NET the string GUID, that would be ideal.
Output from REST call
"{\"sa\":[\"BHDQ9TLPeaeVuSSgXv9bsOIVFUWbOpivMKhGki7YPLzIXEyHuxRAZhDgts2sEcBQpLBuKJZCtcmSlzWZ9iK0AAA=\",\"BAhyo7T0Wq1WBLXnyN4vo1L94rWLhCCv4DqROi+p9XHO6UeS0Gw6xh1JAKOtXBU2fA432LkNqng8cUt1eAX0bqs=\",\"BGFmyTreWY5pICAcf3itoqbfhs5brOmIDLNF3V7p7slPYdCSVhwWUT5mHD6Lb5kNi\/Qy9tracNUtVgvo3f51FrI=\",\"BMV7RIwoz+LdFgD2fq7UZ7E88KFq\/03381NDYFIKYgUKxEzuXoj6hZfSB0slX5fdaL44Lf6i\/UjDzPQt2XUG8NE=\",\"BL8BnU5WvFn7vIlKi14dWsqykNf1\/nmE55YXFGwLx9Qu3VvDblULt\/U8CXPI1vD8+wMXCRnkunXqxlsFqgghf8w=\"],\"sb\":[\"BInTtgTAn\/zkmrkporhV5DvPZRq5YWm8e\/m02oq55UfY3RxIhOplJgwLjgKMHKYDthYEBcqNNNuVbbWnbtKVAqA=\",\"BJbh5y95wHGjmAPDFNqgewnBxtqVke0sloDD2S3IdrWZ95JfP77rtXZ4lTG8g9PuTLJbl4exZUnM16260WxJ9wU=\",\"BKevE9i2J8CicXHX3elCoQPEpTOmJyGOlBskIbFMFGQFhJ5TD7N1221rhhH9HY6DsfRojmefozsQYzo7Pokp+Hg=\",\"BJbVTRyh8WwCxfR7jRXnran4td7k5+vEfM+HWxeAibneSjdMRQ1Fg6QxKLu+Zu1aPdXqD8M29kABOTAiYopVuQE=\",\"BFv3alDqjo7ckdB2vuxJ15Gur1xsgATjLe9drt\/XU9AkbN+AELCv+mF1Xy8+83L2A1p8aGxF4b7dsrMed27u1j4=\"],\"sz\":\"BF1IiqMz0KmT4gZN6euJquWFt2UmVjyOEdaX0jH8uQMAPG8DBoyneT2PJ9NQTE2xBOP9TtAb1d2O+iCojFqzkvI=\"}"
The output above comes from Chrome. I'm not sure if Chrome adds additional quotes, etc but when I debug System.String on the server, I see the same thing being sent to the WCF service.
The end-usage for this will be a Chrome and Firefox plug in
Well if I am correctly understanding:
You get JSON from a blackbox service. It contains some properties and values. You want to add a new property with some GUID and send it to browser.
If this is correct, try following:
var json=<WHAT YOU GET FROM SERVICE>;
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
obj.sid="this is the new session id"; //ADD NEW PROPERTY
var j=JsonConvert.SerializeObject(obj); //GET BACK JSON STRING WITH NEW PROPERTY
Of if you just want to add session id on client side (inside your plugin) the utilize JSON2 javascript library and use following code (as also suggested by Josh in comments):
var o = JSON.parse(<REST OUTPUT>);
o.sid = <YOUR SESSION ID>;
To convert back to JSON string.
var jsn = JSON.stringify(o);
There is no way to modify that particular response without breaking existing clients. If you can break existing clients, or if you are working with clients that you control, you could wrap the object in another object, setting two keys: GUID and data. For example:
var json = JsonConvert.SerializeObject(new {
data = foo,
GUID = bar,
});
Where bar is the GUID that you want to use, and foo is one of two things:
The JSON string from the response. This will result in the final object looking like so:
{
data: "{\"sa\":[\"BHDQ9TLPeaeVuSSgXv9bsOIVFUWbOpivMKhGki7YPLzIXEyHuxRAZhDgts2sEcBQpLBuKJZCtcmSlzWZ9iK0AAA=\",\"BAhyo7T0Wq1WBLXnyN4vo1L94rWLhCCv4DqROi+p9XHO6UeS0Gw6xh1JAKOtXBU2fA432LkNqng8cUt1eAX0bqs=\",\"BGFmyTreWY5pICAcf3itoqbfhs5brOmIDLNF3V7p7slPYdCSVhwWUT5mHD6Lb5kNi\/Qy9tracNUtVgvo3f51FrI=\",\"BMV7RIwoz+LdFgD2fq7UZ7E88KFq\/03381NDYFIKYgUKxEzuXoj6hZfSB0slX5fdaL44Lf6i\/UjDzPQt2XUG8NE=\",\"BL8BnU5WvFn7vIlKi14dWsqykNf1\/nmE55YXFGwLx9Qu3VvDblULt\/U8CXPI1vD8+wMXCRnkunXqxlsFqgghf8w=\"],\"sb\":[\"BInTtgTAn\/zkmrkporhV5DvPZRq5YWm8e\/m02oq55UfY3RxIhOplJgwLjgKMHKYDthYEBcqNNNuVbbWnbtKVAqA=\",\"BJbh5y95wHGjmAPDFNqgewnBxtqVke0sloDD2S3IdrWZ95JfP77rtXZ4lTG8g9PuTLJbl4exZUnM16260WxJ9wU=\",\"BKevE9i2J8CicXHX3elCoQPEpTOmJyGOlBskIbFMFGQFhJ5TD7N1221rhhH9HY6DsfRojmefozsQYzo7Pokp+Hg=\",\"BJbVTRyh8WwCxfR7jRXnran4td7k5+vEfM+HWxeAibneSjdMRQ1Fg6QxKLu+Zu1aPdXqD8M29kABOTAiYopVuQE=\",\"BFv3alDqjo7ckdB2vuxJ15Gur1xsgATjLe9drt\/XU9AkbN+AELCv+mF1Xy8+83L2A1p8aGxF4b7dsrMed27u1j4=\"],\"sz\":\"BF1IiqMz0KmT4gZN6euJquWFt2UmVjyOEdaX0jH8uQMAPG8DBoyneT2PJ9NQTE2xBOP9TtAb1d2O+iCojFqzkvI=\"}",
guid: "00000000-0000-0000-0000-000000000000"
}
And you would get at the data through two calls to JSON.parse (or the equivalent).
The deserialized object from the JSON response. This will result in the final object looking like so (most data removed for brevity sake):
{
data: {
sa: [],
sb: [],
sz: ""
},
guid: "00000000-0000-0000-0000-000000000000"
}
And you would access data through response.data.
Why any modification can break existing clients
Where the current response is an object, there are only a few ways to modify it:
Injecting a key into the object. This assumes that no client uses Object.keys() or in any way iterates the key set (e.g. for (k in obj)). While this may be true, this is an assumption.
Adding another object to the end: }, {. Doing so would require that the response be transformed into an array:
[{}, {}]
This would break any client that is assumes the response is an object.
Wrapping the current response in a surrounding object (as proposed above). This as well breaks any clients that assumes a certain structure for the response.
{data:{}, guid: ""}

JSON Data format

Not very familiar with JSON data and how to create it using JavaScript.this is what i am trying
i have created two JS variables
var json={};
var json1={};
i have some certain loops to iterate data and loops like
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=JSON.stringify(json);
}
Doing this i am getting following output
Required: "{"Center":"radio_Required_Center_0,radio_Required_Center_1,","Left":"radio_Required_Left_0,"}"
which is not a valid JSON format.My idea id to create a outer-key say Required and than an inner one's in my case Center and Left
so that i can iterate each value with respect to key Center (i can break the string based on ')
i am not sure how to create correct structure and i don't want to do it on server side which can be done easily.
any solution or hint will really be helpful.
Edit
var data= JSON.stringify(json1);
giving following output
{"Required":"{\"Center\":\"radio_Required_Center_0,radio_Required_Center_1,\",\"Left\":\"radio_Required_Left_0,\"}"}
which is valid JSON data, now i need to execute some code based on the data in the JSON and here are my requirements
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
My real challenge is at step number 2 and 3 where i need to fetch the keys and its associated values and those key and not predefined so i can not access them based on there name.
I am thinking of a way to get key and its values without hard coding key names and execute my logic.
is it possible in by this approach or not?
If you're using a modern version of Javascript, it comes with JSON functions built-in.
var jsonString = JSON.stringify(jsobject);
...to convert a JS object into a JSON string.
(See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)
and
var jsOject = JSON.parse(jsomString);
...to convert back in the other direction.
(see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)
The only time you need to worry about this not being built-in is if you're using an old browser - for example, older versions of IE. However, in this case, there are polyfill libraries like this one that you can load which will implement the above syntax for you.
If you're just trying to compose one big JSON object, you don't need to stringify one JSON object before adding it to another... So instead of doing JSON.stringify(json) you can just do json1[outerKey]=json
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=json;
}
try jsonlint.com to validate your JSON
This is valid:
{
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
This is valid too:
{
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
This isn't:
Required: {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
using JSON.stringify() is the right way of converting javascript objects to JSON string format. However if you want to put it in a variable you should do that first, later in the last step you convert to JSON string.
var output = { "Required": yourpreviousjsonvar },
jsonString = JSON.strinify(output);
EDIT:
You need to process the data first you probably won't even need the JSON string if I understand you right. (=> if however you already got a string you need it parsed first. Do it using JSON.parse(yourjsonstring))
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
having this as variable:
var a = {
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
// step 1
console.log(a.Required);
// step 2
console.log(a.Required.Center);
console.log(a.Required.Left);
// step 3
var center = a.Required.Center.split(',');
var left = a.Required.Left.split(',');
// step 4
for(var i = 0; i<center.length; i++){
console.log("doing somthing with", center[i]);
}
Here is a fiddle => use Chrome/safari/Opera's developpertools and check the console to check the output. Or use firebug (in firefox) Or IE9 or greater (F12).
Use native Javascript toSource :
var obj= new Object();
var obj1= new Object();
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
obj.innerKey=jsonValues;
}
obj1.outerKey=obj;
}
json = obj.toSource();
json1 = obj1.toSource();

Categories