I was trying to assign value to a javascript variable in django. I need the value of javascript variable like.
var chartData = [{
section: "Czech Republic",
attempted: 301.90
}, {
section: "Ireland",
attempted: 201.10
}];
In my django view I am using the following code to generate and render the json data.
i = 0
chart1Data = []
while(i<len(totalSectionsJson)):
chart1Data.append({'section':totalSectionsJson[i].encode('utf8'),'attempted':sectionTotalAttempted[i]})
i = i+1
chart1DataExport = json.dumps(chart1Data)
In the template I am using var chartData = {{chart1Data|safe}}; to assign the javascript variable. But I am getting the data like
var chartData = [{"attempted": 0, "section": "section"}, {"attempted": 0, "section": "section2"}, {"attempted": 0, "section": "section3"}];
I need to eliminate the quotes from attempted and section. How can I do that?
Related
I am currently trying to merge two Json files - one that is nested and one that is flat:
"ampdata": [
{
"nr": "303",
"code": "JGJGh4958GH",
"Anr": "AVAILABLE",
"ability": [ "" ],
"type": "wheeled",
"conns": [
{
"nr": "447",
"status": "",
"version": "3",
"format": "sckt",
"amp": "32",
"vol": "400",
"vpower": 22
}
]
}
[ {
"nr" : 91643421,
"Anr" : "Real",
"Title" : null,
"Comp" : null,
"Name" : "Smith",
"CompanyName" : "WhiteC"
}]
My current Approach is:
var flowFile = session.get();
if (flowFile != null) {
var StreamCallback = Java.type("org.apache.nifi.processor.io.StreamCallback")
var IOUtils = Java.type("org.apache.commons.io.IOUtils")
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets")
flowFile = session.write(flowFile,
new StreamCallback(function(inputStream, outputStream) {
var text = IOUtils.buffer(inputStream)
var obj = JSON.parse(text)
var neu = [];
var neuesObjekt = {};
for (var i = 0; i < obj.ampdata.length; i++) {
var entry = obj.ampdata[i];
if(obj.ampdata[i].nr != obj2.nr) {
obj2.nr = obj.ampdate[i].nr
}
}
outputStream.write(JSON.stringify(newObj, null, '\t').getBytes(StandardCharsets.UTF_8))
}))
flowFile = session.putAttribute(flowFile, "filename", flowFile.getAttribute('filename').split('.')[0]+'_translated.json')
session.transfer(flowFile, REL_SUCCESS)
How do I parse two flowfiles that are incoming at the same time? I do like to work with both at the same time as I have to compare them at several positions. I can not figure out how I can avoid overwriting the first flowfile.
I had another Approach with using the MergeConent-Processor, but the result was just the concatenation of the both Jsons in a way that was not a valid Json anymore. Anyway I do prefer the Javascript attempt more, I just need your help in figuring out, how to do it in a proper way.
i think you can use merge content with parameters:
merge format: binary
header: [
footer: ]
demarcator: ,
by this merge of two json files into one will produce a valid json (array).
then, if you need to reformat json - you still can use ExecuteScript processor...
and you don't need to implement join files logic.
PS: to get two files from input queue use this type of code:
var flowFiles = session.get(2);
if(!flowFiles)return;
if(flowFiles.size()!=2){
session.transfer(flowFiles); //return files back to input queue
return;
}
//we have exactly two files. let's process them...
var flowFile1 = flowFiles[0];
var flowFile2 = flowFiles[1];
//read each, parse, apply logic, write result
...
when my ajax call completes an array of json is returned
for my angular data binding to work perfectly, i need to merge all values in to a single JSON file. I have tried $.extend(), it's giving following output
Need a solution for this
for example if my response looks like this:
[0:"{'test':'test'}", 1:"{'test':'test'}", 2:"{'test':'test'}",3: "{'test':'test'}"];
the output i need is :
{ test':'test', 'test':'test', 'test':'test', 'test':'test' }
Edit:
The final value will be associated to the ng-model automatically.
desired output example:
{
"unique_id": 172,
"portfolio": "DIGITAL",
"bus_unit": "dummy",
"project_phase": "",
"test_phase": "SIT",
"project": "Google",
"golivedate": "03/09/2016",
"performance": "Green",
"summary": "jgnbfklgnflknflk",
"last_updated": "",
"risks_issues": "gfmngfnfglkj",
"project_start": "03/16/2016",
"batchLast_run": "",
"custom_project": "1",
"test_execution_id": 5456,
"unique_id": 172,
"test_execution_id": 5456,
"pass": 8,
"fail": 8,
"blocked": 8,
"in_progress": 8,
"no_run": 8,
"not_available": 0,
"total": 8
}
From what I understand you are trying to convert array of Json data into one singel json data. So you have array of values but you would want all of them in one variable. Try this
var testData = ["{'test':'test'}", "{'test':'test'}", "{'test':'test'}", "{'test':'test'}"];
var finalData ="";
$.each(testData,function(index,value){
finalData += value +',';
});
finalData = finalData.replace(/\},\{/g,',').slice(0, -1);
document.write(finalData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Map just applies the function to every element in the array.
var arrayOfJSON = ...
var arrayOfObjects = arrayOfJSON.map(function (jsonString){
return JSON.parse(jsonString)
})
var jsonStringWithAllObjects = JSON.stringify(arrayOfObjects)
If you use underscore.js then can easily
like:
var list = [{"test1": "test1"}, {"test2": "test2"}, {"test3": "test3"}];
var newList = _.extend.apply(null,[{}].concat(list));
then output will be
{ test1: "test1", test2: "test2", test3: "test3" }
Iterate over the array, convert every value to a JSON object, concatenate and then convert to a string back.
If you need fo this more times, you probably should make this a function.
I'm trying to do a WEB based power management system and I'm using PLC Siemens S7-1200. I want to use some tags from PLC in javascript to build a chart. When I use:
var chartData = [{
country: "USA",
visits: 230
}, ];
In chart code this works fine.
Now I want to use instead of the fixed numeric value "230" a variable value with the label "Voltage" as tag in the PLC. How can I do this?
If you have the value in the variable voltage, just use that variable in the object:
var chartData = [{
country: "USA",
visits: voltage
} ];
DEMO
{
"data": [
{
"date": "2013-03-07",
"id": "2",
"vt_color": "#548dd4",
"vt_name": "follow up",
"duration": "20",
"time_booked": "12:00:00",
"stats": "booked",
"doctor_id": "00002",
"patient_id": "00003"
},
{
"date": "2013-03-08",
"id": "3",
"vt_color": "#76923c",
"vt_name": "ultrasound",
"duration": "30",
"time_booked": "08:00:00",
"stats": "booked",
"pt_name": "demo patien",
"dr_name": "Momen Alzalabany",
"doctor_id": "00002",
"patient_id": "00009"
}
]
}
what i want is to create another array out of this including vt_name,vt_color and index of data
so i use jquery
var words = [];
$.each(arr['data'],function(ref){
words[this.doctor_id].push({name: this.vt_color,color: this.vt_name,index:ref});
});
console.log(koko);
FAIL : words[this.do_id] is not defined....
how can i do this ? i want outcome to be
sorry i'm a newbie with json/js
i want outcome in php would be
['00002'=>[
['name'=>'follow up','color'=>'#548dd4',index=>[0,3,4]],
['name'=>'ultrasound','color'=>'#769dd4',index=>[1,5,8]]
]
]
Change the type of words to object (not array), since you want a map with a string (e.g. '00002') as key:
var words = {};
You want do add to an array which does not exist. You need to create it first:
words[this.doctor_id] = words[this.doctor_id] || []; // creates an array if not already existing
words[this.doctor_id].push({name: this.vt_color,color: this.vt_name,index:ref});
This is my sample JSON file , which im trying to parse and read the values ....
C = {{
"Travel": {
"ServiceProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
},
"BusProvider": {
"Name": "SRS",
"Rating": "3 stars",
"Rates": "Nominal",
"Features": {
"OnlineBooking": "Yes",
"SMS_Ticket": "No"
},
"UserDetails": {
"Name": "Jack",
"Age": "33",
"Gender": "Male"
}
}
}
}
I'm pretty new to JS , and i need to access the nested elements in a generic fashion.
Im not able to extract the details properly. Im getting stuck accessing nested the child elements.
The problem for me is that i wont always know the names of the "key's' to acess them , the JSON will be dynamic , hence i need a generic mechanism to acess the nested child elements. The Nesting can go upto 3 -4 levels.
what notation do we use to access the key / value pairs when the nesting is deep.
Any Help would be appreciated.
ater desirializing your object you can do this
var resultJSON = '{"name":"ricardo","age":"23"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key
alert(k + ' is the key)
}
you can do it using recursively offcourse like this - Link Here
the way is the same just adapt to your example
For dynamic access you can use brackets notation i.e. var json = {nonKnown: 1}; now you can access it like that:
var unknowPropertyName = "nonKnown";
var value = json[unknownPropertyName];
But if you can not even define dynamically name of the property, then you should use
for(variableName in json){
if(json.hasOwnProperty(variableName)){
console.log(variableName);
}
}
You should get the basic idea from this. Good luck