how to convert in json object?
I also tried the following.
$scope.getEval = function (str) {
return eval(str);
};
try {
s = $scope.getEval("\nexports = { emptyFunction: function () { \n exit(); }, getUserName: function () { if (!variable.global_name) { exit(changeFlowAndStep('get_user_name', 0, {global_first_time_done: false}, true)); } else { exit({variable:{global_first_time_done: true}}); } }}")
for (var i in s) {
s[i] = s[i].toString();
}
$scope.s = s;
console.log($scope.s)
} catch (e) {
console.log(e);
}
If you have a javascript object, it is easy to generate a JSON string with JSON.stringify() and if you have a JSON string, it is easy to generate a javascript object with JSON.parse()
// going from JSON to JS object...
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
console.log(obj);
console.log(obj.count);
// from JS object to JSON string...
var str = JSON.stringify(obj);
console.log(str);
from:
Parse JSON in JavaScript?
Convert JS object to JSON string
Your use of eval works, as you can see when you call console.dir($scope.s);
It is possible to use json = JSON.stringify(obj); and obj = JSON.parse(json);. However it appears JSON.stringify ignores object fields with a function as a value. That is your string is not a useful json string.
Related
I am scraping data from a URL containing a csv. The format of the data I'm scraping is like this:
I am doing this in Node.js and using the nodejs-requestify package: https://www.npmjs.com/package/requestify
When I console the response.getBody() it's in the exact same format as the screenshot provided.
I am trying to convert this to a JSON array that I can iterate over in a loop to insert the values into a database, however, am struggling to get the data into JSON format.
I've tried splitting the array in multiple ways (comma, single quote, double quote). I've tried JSON.parse() and JSON.stringify() (and both in combination).
Here is the code I'm using. Ultimately when I console.log rows in the loop, this is where it should be in JSON format, however, it's just coming in as comma separated values still.
requestify.get('URL').then(function(response) {
// Get the response body
var dataBody = response.getBody();
var lineArray = dataBody.split('\r\n');
var data = JSON.parse(JSON.stringify(lineArray));
for(var s = 0; s < data.length; s++) {
var rows = data[s];
console.log(rows)
}
});
There is a basic misundertanding I think
var lineArray = dataBody.split('\r\n');
lineArray now contains something like
"a", "b", "c"
but for doing something like
var data = JSON.parse(lineArray);
you need lineArray to be
{ "a":"1", "b":"2", "c":"3" }
I think you need something like
const lineData = lineArray.split(',');
const keys = ["name", "age", "gender"];
const jsonLineData = {};
keys.forEach((key, index) => {
jsonLineData[key] = lineData(index);
});
I solved this by using csvtojson and aws-dsk since my csv is hosted on S3.
async function startAWS(db){
//Retrieve AWS IAM credentials for the 'master' user
var awsCredentials;
try{
awsCredentials = await retrievePromise(config.get('aws'));
}
catch (e) {
console.log({error:e},'startAWS error');
}
//Setup the AWS config to access our S3 bucket
AWS.config = new AWS.Config({
accessKeyId : awsCredentials.principal,
secretAccessKey :awsCredentials.credential,
region:'us-east-1'
});
//Call S3 and specify bucket and file name
const S3 = new AWS.S3();
const params = {
Bucket: '***',
Key: '***' //filename
};
//Convert csv file to JSON
async function csvToJSON() {
// get csv file and create stream
const stream = S3.getObject(params).createReadStream();
// convert csv file (stream) to JSON format data
const json = await csv().fromStream(stream);
//connect to DB and continue script
db.getConnection()
.then(async (conn) => {
if(json.length) {
for(var s = 0; s < json.length; s++) {
var rows = json[s];
const insert = await conn.query(
'SQL HERE'
);
}
}
})
};
csvToJSON();
}
I have a GET request that sends back a JSON object structured like this:
{"ID":5176,
"DateFrom":"8/29/2018",
"DateTo":"8/29/2018",
"Units":[{"Key":"Value","Key2": "Value2"}]
}
I cannot access Units[0] value. I have tried the following:
testFunction(){
this.service.getJSON(params)
.subscribe((data) => {
this.model = data;
this.dateFrom = this.model.DateFrom;
this.dateTo = this.model.DateTo;
this.unit = this.model.Units.Key;
console.log(this.unit); //undefined
});
}
}
ngOnInit() {
this.testFunction();
}
What am I missing?
You should use
this.unit = this.model.Units[0].Key;
instead of
this.unit = this.model.Units.Key;
since Units.Key is undefined
Since Units is an array of JSONs and the array contains only one element.
It should be accessed by Units[0].
Units[0] is now a JSON, Key property is needed now.
There are 2 ways to access it
Units[0].Key
Units[0]['Key']
The final code should look like
testFunction(){
this.service.getJSON(params)
.subscribe((data) => {
this.model = data;
this.dateFrom = this.model.DateFrom;
this.dateTo = this.model.DateTo;
//first method
//this.unit = this.model.Units[0].Key;
// second method
// this.unit = this.model.Units[0]['Key'];
console.log(this.unit); //undefined
});
}
}
ngOnInit() {
this.testFunction();
}
I got a requirement to convert .properties file to JSON object using angular js.
I have no clue how to achive this, i searched in net but did not found the solution. Could you please help me with this.
.properties file contains
a.b.10=M
a.b.11=M50
a.b.12=M508
Output should be
{"a":{"b":{"10":"M","11":"M50","12":"M508"}}}
Try this
var str1 = "a.b.12=M508";
var str2 = "a.b.10=M";
var str3 = "a.b.11=M50";
var result = {};
function createObject(str) {
str.split('.').reduce((obj, key) => {
if (!obj[key] && !key.includes('='))
obj[key] = {};
else if (key.includes('=')) {
var keys = key.split('=');
obj[keys[0]] = keys[1];
}
return obj[key];
}, result);
return result;
}
createObject(str1);
createObject(str2);
createObject(str3);
console.log(result);
request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;
var time = Math.floor((Date.now() - Date.parse($scope.cases[i].date_case_modified))/(60000*60*24));
$scope.cases.duration.push(time);
}
});
Inside the controller I am trying to tack on the cases.duration onto the cases object but it wont add it onto the object that is returned. Any ideas?
I think you just need to introduce a forEach as shown here:
request = myService.getCases();
request.then(
function(payload) {
$scope.cases = payload.data;
angular.forEach($scope.cases, function (el) {
var time = Math.floor((Date.now() - Date.parse(el.date_case_modified))/(60000*60*24));
el.duration = time;
});
}
});
Hope this helps
I use JSON.stringify(data); to return json
here is my code
var data;
programService.query({
id: $routeParams.id
}, function (result) {
data = { 'program': result };
data= JSON.stringify(data);
$scope.setPagingData(data,page,pageSize);
});
$scope.setPagingData = function(data, page, pageSize){
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.myData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
json data
{programId:1,
programName:project1,
programContent:content1,
programStartDate:2012-01-01,
templateId: "1"}
and the result will be p , r, o...
not a programId, 1, programName, project1.....
any ideas?
I'm not sure exactly what you are trying to do, but let me just point out some things in your code that could potentially point you in the right direction.
First, your JSON data (which I assume you mean as the result from your server:
{programId:1,
programName:project1,
programContent:content1,
programStartDate:2012-01-01,
templateId: "1"}
is pretty decently mal-formed. Double-quotes around both keys and values is proper JSON format (values that are numbers don't need quotes).
Second, assuming your JSON data is indeed how you want and expect it to be, in your callback function:
...
}, function (result) {
data = {
'program': result
};
...
});
...
result is a STRING (since JSON is simply a text-based serialization format and is always a string), meaning
data = {
'program': result
};
results in data looking like a JS object like this:
{ 'program' : '{programId:1, programName:project1, programContent:content1, programStartDate:2012-01-01, templateId: "1"}' }
Perhaps you meant to convert the JSON into a native JS object, in which case JSON.parse(result) is what you are looking for.
data = {
'program': JSON.parse(result)
};
data now looks like a JS object like this (assuming your JSON is well-formed, otherwise the parse function will break):
{
"program" : {
"programId" : 1,
"programName" : "project1",
"programContent" : "content1",
"programStartDate" : "2012-01-01",
"templateId" : "1"
}
}
Third, back to your callback function:
...
}, function (result) {
...
data= JSON.stringify(data);
$scope.setPagingData(data,page,pageSize);
});
...
data= JSON.stringify(data); converts the given data into a JSON string. If this is what you intend, then carry on!
Fourth, in your $scope.setPagingData function,
$scope.setPagingData = function(data, page, pageSize){
var pagedData = data.slice((page - 1) * pageSize, page * pageSize);
$scope.myData = pagedData;
$scope.totalServerItems = data.length;
if (!$scope.$$phase) {
$scope.$apply();
}
};
the .slice function and .length attribute are both part of the Array prototype. This means if your passed in data is a JS object, .slice will throw a "has no method slice" error and .length will return undefined.