how to convert into a json object - json

i have a file named 'funcJson.json'
whose content are as follows:
{
"fid":{
"processDate":function ()
{
data=MainMasterarr;
for(var i=0;i<data.length;i++)
{
data[i]['_id'] =data[i]['_id'].substring(0,8);
var mongoId = data[i]["_id"];
var dateObject = new Date( mongoId );
dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );
var date = dateObject.getDate();
var month = dateObject.getMonth()+1;
var year = dateObject.getFullYear().toString();
var yearSub = year.substring(2,4);
if(month<10)
month='0'+ month;
if (date<10)
date='0'+ date;
var dateString = month+'/'+date+'/'+yearSub;
data[i]['fid'] = dateString;
}
} ,
"consoleDate":function ()
{
data=MainMasterarr;
console.log(data[0]['fid']);
}
}
}
now i trying to read this file and convert the file content to json object.
when i equate the above json to a variable.it works like json object but now when i m trying to read it from a file it throws error.
my client side code is below:
function fetchFileData(fn,callback)
{
var fileName='funcJson.json';
var request = new goog.net.XhrIo();
var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
"fileN":fileName,
}));
goog.events.listen(request, "complete", function()
{
if (request.isSuccess())
{
if(request.getResponseText() == 'fails')
{
callback("error");
return;
} //if response fails
else
{
var response = request.getResponseJson();
fileData=response;
console.log(fileData);
callback(response);
}//else
} //if request is success
});//listen event
request.send(fetchFileUrl, "POST", data);
//return fileData;
};
and server side code is as follows
function fetchFile(req,res,params)
{
var fs = require('fs');
//var configJson = {};
var fileName=params.fileN;
fs.readFile(fileName, 'utf8', function (err, data) {
if (err)console.log(err);
//console.log(data);
//configJson = JSON.parse(data);
res.writeHead(200, {
"Content-Type": "text/plain"
});//res.writeHead
res.write(data);
res.end();
});
}
If i take a normal json with functions in it give me result as object which i can instantiate to variable and use that variable as json object.but as i give function declaration in json file.it throws error.
plz guide

changed the json format and it worked
format is as follows:
{
"fid":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
},
"nloc":{
"processDate":"function (){data=MainMasterarr;for(var i=0;i<data.length;i++){data[i]['_id'] =data[i]['_id'].substring(0,8);var mongoId = data[i]['_id'];var dateObject = new Date( mongoId );dateObject = new Date( parseInt( mongoId, 16 ) * 1000 );var date = dateObject.getDate();var month = dateObject.getMonth()+1;var year = dateObject.getFullYear().toString();var yearSub = year.substring(2,4);if(month<10)month='0'+ month;if (date<10)date='0'+ date;var dateString = month+'/'+date+'/'+yearSub;data[i]['fid'] = dateString;}}",
"consoleDate":"function (){data=MainMasterarr;console.log(data[0]['fid']);}"
}
}

Related

find all label and product in json python

I'm trying to find all label and product in text/javascript, but I don't have any idea to how do it. I'm trying to parse label, id and products.
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});
It's possible to do that less elegantly but without regex - just a series of splits and clean ups:
import json
code = [your script above]
code2 = html.replace('½','').split('":"Taglia","options":[{')[1].split('}]}},"template"')[0].split('},{')
for i in range(len(code2)):
data = json.loads('{'+code2[i]+'}')
print(data['id'],data['label'])
Output:
730 36
731 37
732 38
733 38
etc.
You can regex out javascript object and pass to json then parse out info
import re
import json
#html = response.content from requests
html = '''
var spConfigDisabledProducts = [-1
, '290058', '290060', '290061', '290062', '290063', '290065', '290071', '290073', '290075', '290076', '290077', '290078' ];
var spConfig = new Product.Config({"attributes":{"959":{"id":"959","code":"aw_taglia","label":"Taglia","options":[{"id":"730","label":"36 ½","price":"0","oldPrice":"0","products":["290058"]},{"id":"731","label":"37 ½","price":"0","oldPrice":"0","products":["290060"]},{"id":"732","label":"38","price":"0","oldPrice":"0","products":["290061"]},{"id":"733","label":"38 ½","price":"0","oldPrice":"0","products":["290062"]},{"id":"734","label":"39","price":"0","oldPrice":"0","products":["290063"]},{"id":"735","label":"40","price":"0","oldPrice":"0","products":["290064"]},{"id":"736","label":"40 ½","price":"0","oldPrice":"0","products":["290065"]},{"id":"737","label":"41","price":"0","oldPrice":"0","products":["290066"]},{"id":"738","label":"42","price":"0","oldPrice":"0","products":["290067"]},{"id":"739","label":"42 ½","price":"0","oldPrice":"0","products":["290068"]},{"id":"740","label":"43","price":"0","oldPrice":"0","products":["290069"]},{"id":"741","label":"44","price":"0","oldPrice":"0","products":["290070"]},{"id":"742","label":"44 ½","price":"0","oldPrice":"0","products":["290071"]},{"id":"743","label":"45","price":"0","oldPrice":"0","products":["290072"]},{"id":"744","label":"45 ½","price":"0","oldPrice":"0","products":["290073"]},{"id":"745","label":"46","price":"0","oldPrice":"0","products":["290074"]},{"id":"746","label":"47","price":"0","oldPrice":"0","products":["290075"]},{"id":"747","label":"47 ½","price":"0","oldPrice":"0","products":["290076"]},{"id":"748","label":"13.5","price":"0","oldPrice":"0","products":["290077"]},{"id":"749","label":"48 ½","price":"0","oldPrice":"0","products":["290078"]}]}},"template":"#{price}\u00a0\u20ac","basePrice":"130","oldPrice":"130","productId":"290059","chooseText":"Seleziona","taxConfig":{"includeTax":true,"showIncludeTax":true,"showBothPrices":false,"defaultTax":0,"currentTax":0,"inclTaxTitle":"Incl. Tasse"}});
jQuery("#attribute959 option").each(function () {
var option = jQuery(this);
var id = option.attr('value');
jQuery.each(spConfig.config.attributes, function () {
jQuery.each(this.options, function () {
if (this.id == id) {
if (spConfigDisabledProducts.indexOf(this.products[0]) >= 0) {
option.data('disabled', true);
}
}
});
});
});'''
p = re.compile(r'Product\.Config\((.*?)\)', re.DOTALL)
data = json.loads(p.findall(html)[0])
for attribute in data['attributes']:
print('-----------------attribute--------------')
print('label = ' + data['attributes'][attribute]['label'], 'id = ' + data['attributes'][attribute]['id'])
print('-----------------options----------------')
for product in data['attributes'][attribute]['options']:
print('label = ' + product['label'], 'id = ' + product['id'], 'product = ' + product['products'][0])

Angular 2 - Parsing Excel worksheet to Json

I have an Excel file with the following content:
Inside my component.ts, I extract the Excel's content as follow:
var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i){
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
var jsonOut = JSON.stringify(json);
console.log("test"+jsonOut);
}
oReq.onerror = function(e) {
console.log(e);
}
oReq.send();
XLSX.utils.sheet_to_json will format JSON as follow:
However, I would like the JSON to be as follow:
Most probably I would need to manually create the JSON, but can anyone help me point to the direction on how I can accomplish this?
In your case we need to modify the JSON data by looping over XLSX.utils.sheet_to_json JSON object:
// This object will contain the data in the format we want
var finalObj = { "object": []};
// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
lockey, firstCondKey, secondCondkey;
// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;
// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
// we don't want to consider name of columns which is first element of array
if(!index) return;
// Go inside only if not null
if(value[0]) {
// For Location
finalObj.object.push(createObj(value[0]));
locIndex++;
// We also need to store key names to push it's children
lockey = value[0];
firstCondIndex = -1;
}
if(value[1]) {
// For First Condition
finalObj.object[locIndex][lockey].push(createObj(value[1]));
firstCondIndex++;
firstCondKey = value[1];
secondCondIndex = -1;
}
if(value[2]) {
// For Second Condition
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
secondCondIndex++;
secondCondkey = value[2];
}
if(value[3]) {
// For Products
// We just push the string
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
}
});
function createObj(val) {
// We need to initialize blank array so we can push the children of that element later on
var obj = {};
obj[val] = [];
return obj;
}
console.log(finalObj);

Convert commits from git into json array/json object not working (Nodejs)

Hello I'm trying to format my json in this when I have a long array [] and then json objects in {}. Right now I am getting a wierd format where the name of my objects are saving in wrong format. e.g rather than "commit":"commitname", its saying as "commit commit name" below is my code that I am using to do this:
function put(error, stdout, stderr) {
var commitsbybranch = JSON.stringify(stdout.split(/\r?\n/).map(function(e) { return e.substring(0);}).filter(function(e) { return e; }));
var commitsObj2 = JSON.parse(commitsbybranch);
console.log(commitsObj2.length);
function toObject(commitsbybranch) {
var ss = {};
for (var i = 0; i < commitsbybranch.length; ++i)
ss[i] = commitsbybranch[i];
return ss;
}
fs.writeFile('reacted/public/testcommitsbybranch.json', commitsbybranch);
}
My json looks like this now:
["commit commitname",","Merge: 27755ba 5c51","Author: Harsharan <harsharan#coolio.com>","Date: Mon Feb 29 18:01:11 2016 +0000","commit commitname2",","Merge: 27755ba 5c51","Author: Harsharan <harsharan#coolio.com>","Date: Mon Feb 29 18:01:11 2016 +0000"]
Please help me resolve it
You need to parse the result of git log 'branchName'. Try this:
function put(error, stdout, stderr) {
var log = stdout.split(/\r?\n/);
var json = [];
var commitInfo = {};
for(var i in log){
var str = log[i];
if(str.match(/^commit\s+/)){
var split = str.split(/^commit\s+/);
commitInfo['commit'] = split[1];
}
if(str.match(/^Author:\s+/)){
var split = str.split(/^Author:\s+/);
commitInfo['Author'] = split[1];
}
if(str.match(/^Date:\s+/)){
var split = str.split(/^Date:\s+/);
commitInfo['Date'] = split[1];
}
if(str.match(/^\s+/)){
var split = str.split(/^\s+/);
commitInfo['message'] = split[1];
}
else if(commitInfo['commit'] != undefined && commitInfo['Author'] != undefined && commitInfo['Date'] != undefined && commitInfo['message'] != undefined){
json.push(commitInfo);
commitInfo = {};
}
}
var commitsbybranch = JSON.stringify(json);
fs.writeFile('reacted/testcommitsbybranch.json', commitsbybranch);
}

Funky IE JSON conversions

When running our AngularJS app in IE11 everything looks great in the debugger, but when our app encodes the data as JSON to save to our database, we get bad results.
Our app obtains a record from our database, then some manipulation is done and then the data is saved back to the server from another model.
Here is the data I got back from the server in the setAttendanceGetSInfo() function below:
{"data":{"Start":"2014-10-16T19:36:00Z","End":"2014-10-16T19:37:00Z"},
This is the code used to "convert the data" to 3 properties in our model:
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: new Date(e).toLocaleDateString(),
examStartTime: (new Date(e)).toLocaleTimeString(),
examEndTime: (new Date(f)).toLocaleTimeString()
});
return result.sInfo;
});
};
fromISO is defined as:
(function(){
var D= new Date('2011-06-02T09:34:29+02:00');
if(!D || +D!== 1307000069000){
Date.fromISO= function(s){
var day, tz,
rx=/^(\d{4}\-\d\d\-\d\d([tT ][\d:\.]*)?)([zZ]|([+\-])(\d\d):(\d\d))?$/,
p= rx.exec(s) || [];
if(p[1]){
day= p[1].split(/\D/);
for(var i= 0, L= day.length; i<L; i++){
day[i]= parseInt(day[i], 10) || 0;
};
day[1]-= 1;
day= new Date(Date.UTC.apply(Date, day));
if(!day.getDate()) return NaN;
if(p[5]){
tz= (parseInt(p[5], 10)*60);
if(p[6]) tz+= parseInt(p[6], 10);
if(p[4]== '+') tz*= -1;
if(tz) day.setUTCMinutes(day.getUTCMinutes()+ tz);
}
return day;
}
return NaN;
}
}
else{
Date.fromISO= function(s){
return new Date(s);
}
}
})()
Take a look at the screenshot of the event model data:
But, if I eval the event model using JSON.stringify(model.event), I get this:
{\"examDate\":\"?10?/?16?/?2014\",\"examStartTime\":\"?2?:?44?:?00? ?PM\",\"examEndTime\":\"?2?:?44?:?00? ?PM\"}
And this is the JSON encoded data that actually got stored on the DB:
"examDate":"¿10¿/¿16¿/¿2014","examStartTime":"¿2¿:¿36¿:¿00¿ ¿PM","examEndTime":"¿2¿:¿37¿:¿00¿ ¿PM"
What is wrong here and how can I fix this? It works exactly as designed in Chrome and Firefox. I have not yet tested on Safari or earlier versions of IE.
The toJSON for the date class isn't defined perfectly the same for all browsers.
(You can see a related question here: Discrepancy in JSON.stringify of date values in different browsers
I would suspect that you have a custom toJSON added to the Date prototype since your date string doesn't match the standard and that is likely where your issue is. Alternatively, you can use the Date toJSON recommended in the above post to solve your issues.
First, I modified the fromISO prototype to this:
(function () {
var D = new Date('2011-06-02T09:34:29+02:00');
if (!D || +D !== 1307000069000) {
Date.fromISO = function (s) {
var D, M = [], hm, min = 0, d2,
Rx = /([\d:]+)(\.\d+)?(Z|(([+\-])(\d\d):(\d\d))?)?$/;
D = s.substring(0, 10).split('-');
if (s.length > 11) {
M = s.substring(11).match(Rx) || [];
if (M[1]) D = D.concat(M[1].split(':'));
if (M[2]) D.push(Math.round(M[2] * 1000));// msec
}
for (var i = 0, L = D.length; i < L; i++) {
D[i] = parseInt(D[i], 10);
}
D[1] -= 1;
while (D.length < 6) D.push(0);
if (M[4]) {
min = parseInt(M[6]) * 60 + parseInt(M[7], 10);// timezone not UTC
if (M[5] == '+') min *= -1;
}
try {
d2 = Date.fromUTCArray(D);
if (min) d2.setUTCMinutes(d2.getUTCMinutes() + min);
}
catch (er) {
// bad input
}
return d2;
}
}
else {
Date.fromISO = function (s) {
return new Date(s);
}
}
Date.fromUTCArray = function (A) {
var D = new Date;
while (A.length < 7) A.push(0);
var T = A.splice(3, A.length);
D.setUTCFullYear.apply(D, A);
D.setUTCHours.apply(D, T);
return D;
}
Date.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
})()
Then I added moment.js and formatted the dates when they get stored:
var SaveAffRow = function () {
// make sure dates on coursedate and event are correct.
var cd = model.a.courseDate;
var ed = model.event.examDate;
var est = model.event.examStartTime;
var eet = model.event.examEndTime;
model.a.courseDate = moment(cd).format("MM/DD/YYYY");
model.event.examDate = moment(ed).format("MM/DD/YYYY");
model.event.examStartTime = moment(est).format("MM/DD/YYYY hh:mm A");
model.event.examEndTime = moment(eet).format("MM/DD/YYYY hh:mm A");
affRow.DocumentsJson = angular.toJson({a: model.a, event: model.event});
var aff = {};
if (affRow.Id != 0)
aff = affRow.$update({ Id: affRow.Id });
else
aff = affRow.$save({ Id: affRow.Id });
return aff;
};
and when they get read (just in case they are messed up already):
var setAttendanceGetSInfo = function (CourseId, PID) {
return setAttendanceInfo(CourseId, PID)
.then(function (result) {
return $q.all([
$http.get("../api/Axtra/getSInfo/" + model.event.Id),
$http.get("../api/Axtra/GetStartAndEndDateTime/" + aRow.Rid)
]);
}).then(function (result) {
var r = result.data;
var e = Date.fromISO(r.Start);
var f = Date.fromISO(r.End);
angular.extend(model.event, {
examDate: moment(e).format("MM/DD/YYYY"),
examStartTime: moment(e).format("MM/DD/YYYY hh:mm A"),
examEndTime: moment(f).format("MM/DD/YYYY hh:mm A")
});
return result.sInfo;
});
};

Read list from json object

I am try to read list from json here id my code:-
List<EmailProvider> list = new List<EmailProvider>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/WidgetXml.xml"));
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//widget");
foreach (XmlNode node in nodes)
{
EmailProvider obj = new EmailProvider();
obj.Name = node["Name"].InnerText;
obj.left = Convert.ToInt32(node["left"].InnerText);
obj.Id = node["id"].InnerText;
obj.IsVisible = Convert.ToBoolean(node["isActive"].InnerText);
long s = Int64.Parse(node["top"].InnerText);
obj.top = s;
obj.desc = node["desc"].InnerText;
list.Add(obj);
}
var result = list.OrderBy(p => p.IsVisible).ToList();
return result.ToArray();
and on view:-
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
alert(data.length);
var st = JSON.stringify(data);
alert(st.length);
});
});
length always show 54 but in array only 4 items. How can i read all recors from array by json from json object.
Thanks in advance.
Try returning a JsonResult from your controller method, using the controller method Json
var result = list.OrderBy(p => p.IsVisible).ToList();
return Json(result.ToArray());
On JavaScript, you should just need to iterate over the array as in:
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
for(var i = 0;i < data.length; i++){
alert(data[i].Name);
}
});
});