The below NodeJS code tries to convert an xml document into json and then parse it.
var fs = require('fs');
var parse = require('jsonml').parse;
var jsonML = parse(fs.readFileSync('myfile.xml'));
var jsondata = JSON.parse(jsonML);
console.log(jsondata.BESAPI.Computer[0].ID);
It works fine, but I am unable to display the correct values. An error is thrown on the line console.log(jsondata.BESAPI.Computer[0].ID);
I am trying to display the ID of each computer in the json object.
Json object
{
"BESAPI": {
"-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"-xsi:noNamespaceSchemaLocation": "BESAPI.xsd",
"Computer": [
{
"-Resource": "api/computer/2431038",
"LastReportTime": "Thu, 26 Feb 2015 14:54:41 +0000",
"ID": "2431038"
},
{
"-Resource": "api/computer/16710075",
"LastReportTime": "Thu, 26 Feb 2015 14:45:18 +0000",
"ID": "16710075"
},
{
"-Resource": "api/computer/3415985",
"LastReportTime": "Thu, 26 Feb 2015 14:50:52 +0000",
"ID": "3415985"
}]
}
}
I get this error:
Without having your original XML, I can't know for sure what's going on, but this experiment may help you with further investigations.
For an XML like
<?xml version="1.0"?>
<BESAPI>
<Computer ID="api/computer/2431038"></Computer>
<Computer ID="api/computer/16710075"></Computer>
</BESAPI>
the output from jsonML looks like this:
[ 'BESAPI',
[ 'Computer', { ID: 'abc123' } ],
[ 'Computer', { ID: 'def987' } ] ]
which doesn't resemble the JSON you gave us, but attempting to parse it gives the error you presented.
So I'm guessing that the output from jsonML isn't parsable JSON, but a nested array of sorts.
Related
I am trying to get a value from a JSON array in Javascript :
The JSON array looks like :
[
{
"_id": 0,
"_entityMetadataList": [
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101696032.jpg",
},
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101694488.jpg",
}
],
"_timeCreated": "Tue Jan 15 06:10:04 2019\n",
"_timeUpdated": "Tue Jan 15 06:10:04 2019\n",
"objectEntity": {
"_id": 0,
"_EntitySiteGUID": -1
}
}
]
How I go about it :
app.post('/sound', function (req, res) {
let entitiesArray = req.body['filter'];
console.log('entitiesArray: ' + JSON.stringify(entitiesArray._entityMetadataList[0]._metadataValue))
(this is in a Node environment, by the way)
I, however keep getting the error :
TypeError: Cannot read property '0' of undefined
Seems you also need to pass the index for revEntitiesArray.
Try this
console.log('revEntitiesArray: ' +
JSON.stringify(revEntitiesArray[0]._revEntityMetadataList[0]._metadataValue))
Maybe this code can help
data = [
{
"_id": 0,
"_revEntityMetadataList": [
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101696032.jpg",
},
{
"_metadataValue": "/storage/emulated/0/DCIM/.thumbnails/1524101694488.jpg",
}
],
"_timeCreated": "Tue Jan 15 06:10:04 2019\n",
"_timeUpdated": "Tue Jan 15 06:10:04 2019\n",
"revObjectEntity": {
"_id": 0,
"_revEntitySiteGUID": -1
}
}
]`
data[0]["_revEntityMetadataList"][0]
Looks like you missed that the outermost reference is an array
revEntitiesArray[0]._revEntityMetadataList[0]._metadataValue
When in doubt, assign each part of your path expression to a local variable and step through with a debugger.
I'm trying to use the ScanFilter to filter a date using dynamoDB.
I tried looking in the docs but can't find how to structure the JSON format.
Currently I have:
"params": {
"TableName": "steprstatus2",
"ScanFilter": {
"lastModified": {
"ComparisonOperator": "BETWEEN",
"AttributeValueList": [
"Wed, 10 Oct 2018 21:09:23 GMT", "Fri, 12 Oct 2018 21:09:23 GMT"
]
}
}
}
I'm not sure what should go in the AttributeValueList, or if I have to modify my date to be a specific format in DynamoDB itself.
Thanks
Looks like I needed to use the BETWEEN comparison operator instead and provide comma separated values in my array of the same data type:
"ScanFilter": {
"lastModified": {
"ComparisonOperator": "BETWEEN",
"AttributeValueList": [
"Wed, 10 Oct 2018 00:02:59 GMT",
"Wed, 10 Oct 2018 23:46:34 GMT"
]
}
}
According to the ScanFilter AWS docs, the AttributeValueList is specified as an array of type -> value maps.
In your case, the array would look something like this:
"AttributeValueList": [
{"S": "Wed, 10 Oct 2018 21:09:23 GMT"},
{"S": "Fri, 12 Oct 2018 21:09:23 GMT"}
]
Note that the Date type is stored as an S (String) DynamoDB type.
Use BETWEEN in FilterExpression with scan query.
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient();
let queryParams = {
TableName: 'tableName',
FilterExpression: '#lastModified BETWEEN :startTime AND :endTime',
ExpressionAttributeValues: {
':startTime': '2018-06-26T18:10:00.000Z',
':endTime': '2018-06-27T18:10:00.000Z'
},
ExpressionAttributeNames: { '#lastModified': 'lastModified' },
ScanIndexForward: false
};
documentClient.scan(queryParams, function (err, data) {
if (err) {
console.log('failure:scan data from Dynamo error', err);
console.log(err);
} else {
console.log('success:scan data from Dynamo data');
console.log(data);
}
});
Not sure what is going on here, I follow the docs, and I get errors, so maybe my table is defined wrong?
function parseGET( data, callback )
{
const params =
{
TableName: data.TableName,
Key:
{
"workOrder": data.workOrder // <--number, not a string
}
};
dynamodb.get( params, ( error, data ) =>
{
if( error )
console.log( 'table ERROR:', error );
...
}
}
Response: "The provided key element does not match the schema"
Response:
{
"statusCode": 200,
"body": "The provided key element does not match the schema",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
}
}
If I do a scan, I get all my data, but I just want to get a single row.
dynamodb.scan( {"TableName": data.TableName}, ( error, data ) =>
...
data:
{
"probeCount": "123",
"rangeCal": "hight",
"ESID": "1",
"rangeNom": "1000",
"nodeCount": "123",
"password": "123",
"cableLength": "456",
"userId": "Onicon",
"usePasswd": "disable",
"elevation": "789",
"workOrder": 789456,
"rangeMax": "1150",
"serialNumber": "3"
}
],
"Count": 11,
"ScannedCount": 11
Getting a single row works in the console, but I can't figure out how to do the same via JS.
Some table details:
Table name myTestTable
Primary partition key workOrder (Number)
Primary sort key -
Point-in-time recovery DISABLEDEnable
Time to live attribute DISABLEDManage TTL
Table status Active
Creation date March 22, 2018 at 1:45:09 PM UTC-7
UTC: March 22, 2018 at 8:45:09 PM UTC
Local: March 22, 2018 at 1:45:09 PM UTC-7
Region (N. California): March 22, 2018 at 12:45:09 PM UTC-8
Have you tried changing the definition of your key to something like...
Key:
{
"workOrder": {"N", data.workOrder} // <--number, not a string
}
you might need to use
data.workOrder.toString()
when defining the key.
Thanks to those who helped.
The end result was I was a little confused (as usual).
data.workOrder was a string of a number, eg. "654" in JSON, not 654.
So the simple solution is to convert it to an actual number:
data.workOrder = parseInt( data.workOrder, 10 );
And now my original query works!
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 9 years ago.
I have not yet used Json so this is very new to me. However, I am working on a system that outputs a json string from which I have to retrieve a single object to use in a js script.
This is the output
{
"SecureZoneSubscriptionList": {
"EntityId": 51350993,
"Subscriptions": [{
"ZoneName": "FACCM Membership",
"ZoneId": "6460",
"ExpiryDate": "9/5/2014 12:00:00 AM",
"SellAccess": true,
"CostPerPeriod": "0.1",
"CycleType": ""
}, ]
}
}
How can I retrieve JUST the expiryDate?
Thanks!
To make it easier to see:
{
"SecureZoneSubscriptionList": {
"EntityId": 51350993,
"Subscriptions": [
{
"ZoneName": "FACCM Membership",
"ZoneId": "6460",
"ExpiryDate": "9\/5\/2014 12:00:00 AM",
"SellAccess": true,
"CostPerPeriod": "0.1",
"CycleType": ""
}
]
}
}
so you would do the following:
var data= {"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""}]}};
var expiryDate = data.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;
if you're retrieving it as a string from a server response, you would JSON.parse to get the object
var data = JSON.parse('{"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""}]}}');
var expiryDate = data.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;
JSON data is simply a javascript object. JSON stands for Javascript Object Notation. Therefore you can get your data the same way as if your were traversing object attributes in JS:
var string = {"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""},]}}
var expiryDate = string.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;
Provided this:
var fromServer = {"SecureZoneSubscriptionList": {"EntityId": 51350993,"Subscriptions": [{"ZoneName": "FACCM Membership","ZoneId": "6460","ExpiryDate": "9/5/2014 12:00:00 AM","SellAccess": true,"CostPerPeriod": "0.1","CycleType": ""},]}}
you would access the ExpiryDate as such:
var expDate = fromServer.SecureZoneSubscriptionList.Subscriptions[0].ExpiryDate;
This is not the best answer. The best answer is by far is to parse the JSON and access your value through the resulting object. Having said that, JSON is a string. When you need data from a string, regular expressions is always an option.
var myString = '{"SecureZoneSubscriptionList": { "EntityId": 51350993, "Subscriptions": [{ "ZoneName": "FACCM Membership", "ZoneId": "6460", "ExpiryDate": "9/5/2014 12:00:00 AM", "SellAccess": true, "CostPerPeriod": "0.1", "CycleType": "" }, ] } }';
var matches = myString.match(/"ExpiryDate":\s?"([^"]*)"/);
alert(matches[1]);
DEMO
i am trying to convert a json value to a flat csv based on the field that is selected by user . My json looks like
var data = {
"_index": "test",
"_type": "news",
"_source": {
"partnerName": "propertyFile 9",
"relatedSources": "null",
"entityCount": "50",
"Categories": {
"Types": {
"Events": [{
"count": 1,
"term": "Time",
"Time": [{
"term": "Dec 9",
"Dec_9": [{
"count": 1,
"term": "2012"
}]
}]
}, {
"count": 4,
"term": "News",
"News": [{
"term": "Germany",
"Germany": [{
"count": 1,
"term": "Election"
}],
"currency": "Euro (EUR)"
}, {
"term": "Egypt",
"Egypt": [{
"count": 1,
"term": "Revolution"
}]
}]
}]
}
}
}};
Ive been able to collect the values of all occurences and store it as a csv, but I want to save the details from the root itself..
If I select Time, the csv output should look like,
"test", "news", "propertyFile 9","null", "50", "Events": "Time", "Dec 9", "2012"
Is it possible to flatten the json.. I will add the json fiddle link to show where Ive reached with this thing..
http://jsfiddle.net/JHCwM/
Here is an alternative way to flatten an object into key/value pairs, where the key is the complete path of the property.
let data = {
pc: "Future Crew",
retro: {
c64: "Censor Design",
amiga: "Kefrens"
}
};
let flatten = (obj, path = []) => {
return Object.keys(obj).reduce((result, prop) => {
if (typeof obj[prop] !== "object") {
result[path.concat(prop).join(".")] = obj[prop];
return result;
}
return Object.assign(result, flatten(obj[prop], path.concat(prop), result));
}, {});
}
console.log(
flatten(data)
);
Your data value is not a JSON (string) - it's an object. There are many ways to 'flatten' this object, may be this little function might be helpful:
var recMap = function(obj) {
return $.map(obj, function(val) {
return typeof val !== 'object' ? val : recMap(val);
});
}
And here's how it can be used. )
There is a npm lib just for this with a lot of options: https://mircozeiss.com/json2csv/
# Global install so it can be called from anywhere
$ npm install -g json2csv
## Generate CSV file
$ json2csv -i data.json -o out.csv --flatten-objects
Try looking here:
http://www.zachhunter.com/2011/06/json-to-csv/
and here:
How to convert JSON to CSV format and store in a variable
Try the following :
http://codebeautify.org/view/jsonviewer
Use Export to CSV button
Check this out to flatten the Json
// Convert Nested Json to Flat Json
// Check the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road, West Bengal 734013, India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]}
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
$.each(data, function(i, e) {
if (e.Children.length>0) {
var ccd = e.Children;
delete e.Children;
finalData.push(e);
loopJson(ccd);
} else {
delete e.Children;
finalData.push(e);
}
});
}
console.log(finalData);
Here is Js fiddle link http://jsfiddle.net/2nwm43yc/