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.
Related
Is there any way to parse/filter the data present in JSON file in a Javascript file.
Basically, I am calling JSON file into my local javascript. I am having trouble in reading specific data and printing.
Can anyone please help.
JSON file contains:
{
"Data": [
{
"name": "John",
"age": 30
},
{
"joined on":"Jan 2015",
"working on": "Automation",
}
]
}
I am trying to read the above JSON file as:
var jfile = require("./Example.json");
var test = JSON.parse(JSON.stringify(jfile))
console.log(test)
I get the output like this:
{ Data:
[ { name: 'John', age: 30 },
{ 'joined on': 'Jan 2015', 'working on': 'Automation' } ] }
From the above, I am interested in accessing/filtering out only one i.e. "name". I would like to print only the value "John" to the console.
I have tried to use the ".filter" method to the JSON.parse method but it throws me an error as:
JSON.parse(...).filter is not a function
Is there any way to perform this activity?
You can access it using . dot notation
var a = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
}
console.log(a.Data[0].name)
filter is an array method.
JSON.parse(...) will not give you an array. It will give you an object with a Data property. The value of that property is an array.
JSON.parse(...).Data.filter.
You can't just ignore parts of your data structure.
If you have multiple items in your array of different shapes, you can use this
Access the Data key with json.Data
map your array to transform its items into names
apply filter(Boolean) to take out those who are undefined
In your case you'll end up with an array containing only one name John
const getName = json => json.Data.map(x => x.name).filter(Boolean);
const json = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation",
}
]
};
console.log(getName(json));
Your JSON's main level is an object (not an array) and only arrays have .filter method.
So filter the array under Data key:
var test = JSON.parse(JSON.stringify(jfile)).Data.filter(/*something*/);
But better if you aren't re-parse JSON:
var test = jfile.Data.filter(/*something*/);
As Quentin mentioned in his comment, What is the use of below statement ?
var test = JSON.parse(JSON.stringify(jfile))
You can directly access the name property from the response.
Try this :
var obj = {
"Data": [{
"name": "John",
"age": 30
},
{
"joined on": "Jan 2015",
"working on": "Automation"
}
]
};
// Solution 1
console.log(obj.Data.map(item => item.name).filter(Boolean));
// Solution 2
console.log(obj.Data.filter(item => item.name).map(elem => elem.name));
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!
I have the below nodejs code that reads contents of baseline.json file and parse it. I then try to display all the Computer ID and LastReportTime. I see an odd behaviour it would not print all the ID and LastReportTime. Also, the results are different every time i run it. The json is big for me to upload here so i uploaded on Json Blob.
Nodejs Code
var fs = require('fs');
try {
var json = JSON.parse(fs.readFileSync('baseline.json'));
for (var obj in json) {
if (json.hasOwnProperty(obj)) {
console.log(obj);
console.log("\n \n");
if (obj == "BESAPI") {
for (var prop in json[obj]) {
console.log(prop);
if (prop == "Computer") {
// loop over Computer dataseries
for (var id in json[obj][prop]) {
console.log(prop + ':' + json[obj][prop][id].ID);
console.log(prop + ':' + json[obj][prop][id].LastReportTime);
}
}
}
}
}
}
} catch (err) {
console.error(err);
}
Raw JSON
https://gist.github.com/anonymous/f27f75879e48c5387a03
In your posted array, LastReportTime and ID are arrays.
Try these lines:
console.log(prop + ':' + json[obj][prop][id].ID[0]);
console.log(prop + ':' + json[obj][prop][id].LastReportTime[0]);
If you pretty print you can see the data comes in two flavors, the top portion followed by the balance of the data in a standard form which does repeat 177 times
{
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"
]
},
{
$: {
Resource: "api/computer/11736335"
},
LastReportTime: [
"Thu, 26 Feb 2015 14:54:41 +0000"
],
ID: [
"11736335"
]
},
I am chopping out many lines her, but it ends normally as
{
$: {
Resource: "api/computer/5520740"
},
LastReportTime: [
"Thu, 12 Feb 2015 02:49:11 +0000"
],
ID: [
"5520740"
]
}
]
}
}
Using nodejs you can pretty print using :
var pretty_print = require('js-object-pretty-print').pretty;
var parsed_data = JSON.parse(data_from_file);
console.log(pretty_print(parsed_data)); // good pretty print
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.
I am trying to use the jqTree from http://mbraak.github.io/jqTree/#tutorial
my page is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Json Parser </TITLE>
<link rel="stylesheet" href="css/jqtree.css">
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/tree.jquery.js"></script>
<script type="text/javascript">
$(function() {
var data = [{"tweetText":"RT #dna: IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan's return http://t.co/PwDniu8sJg","urlsMentioned":[],"usersMentioned":[{"userId":17710740,"screenName":"dna","userName":"dna"}],"source":"Twitter for Android","tweetId":362907208733827100,"reTweetCount":12,"reTweeted":true,"createdDate":"Thu Aug 01 12:06:35 UTC 2013","user":{"location":"","userId":24525170,"screenName":"varuntripathi1","userName":"varun","profileDescription":"","language":"en"},"reTweetedStatus":{"tweetText":"IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan's return http://t.co/PwDniu8sJg","urlsMentioned":["http://dnai.in/bAoD"],"usersMentioned":[],"source":"Tweet Button","tweetId":362606709404991500,"reTweetCount":12,"reTweeted":false,"createdDate":"Wed Jul 31 16:12:31 UTC 2013","user":{"location":"India","userId":17710740,"screenName":"dna","userName":"dna","profileDescription":"We are India’s favourite English daily delivering news, views & analyses. Follow us for real-time news updates. PS: This Twitter feed is not operated by a bot.","language":"en"},"hashTags":[]},"hashTags":[]}]
$('#tree1').tree({
data: data
});
});
</script>
</HEAD>
<BODY>
<div id="tree1">
</div>
</BODY>
</HTML>
It does not show any value. but it is workinf fine for the data
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
];
even though both json are valid one. How would i solve this or any other js available to select the nodes of a json.
jsfiddle
Is there anyother js available to view the json.
Thanks in advance.
As you probably have already figured out, valid JSON != valid data.
You need to provide the constructor with data that corresponds to its requirements.
In the case of jqTree, that is
[
{
"label":"node 1",
"children": [
{
"label": "node 1.1"
},
{
"label": "node 1.2"
}
]
},
{
"label": "node 2"
}
]
etc.
So, you need a function to reformat the data, such as:
function formatData(arr) {
var label, data = [], obj, node;
if(!$.isArray(arr)) {
arr = [arr];
}
console.log(arr);
var l = arr.length, i;
for(i=0; i< l; ++i) {
node = {};
obj = arr[i];
node.label = obj.user.screenName + ": " + obj.tweetText + " (" + obj.createdDate + ")";
if(typeof obj.reTweetedStatus == "object") { //fetch children
node.children = formatData(obj.reTweetedStatus);
}
data.push(node);
}
return data;
}
which will return something like
[{
"label": "varuntripathi1: RT #dna: IPL...Jg (Thu Aug 01 12:06:35 UTC 2013)",
"children": [{
"label": "dna: IPL spot-fixing: Ja...Jg (Wed Jul 31 16:12:31 UTC 2013)"
}]
}]
This creates a tree that looks something like this:
Demo
On a side note, I believe that it will be difficult for you to do what you want with jqTree. It is relatively difficult to customize, in my view.
You can find more configurable jQuery tree widgets, such as jsTree or zTree in jQuery's plugin site.
I created a short example with zTree that produces a the following tree based on your data:
Demo
Your data variable is not a JSON, JSON is a formatted string that you can parse to get a get a javascript object in this case.
A proper JSON string of that object is: var jsonData = "[{"label":"node1","children":[{"label":"child1"},{"label":"child2"}]},{"label":"node2","children":[{"label":"child3"}]}]"
Although I haven't ever used jqTree, I typed your example in Plunker to check how tree work with the three types of data; you data, a json data get from javascript object and the object get from that json data.
http://plnkr.co/edit/Sw3BCigiU69jLkQkAw5U?p=preview
[{
"club":
{ "id":1,"name":"This is a team name"},
"members":
[
{"id":2,"name":"Test Name"},
{"id":3,"name":"Another Name"},
{"id":4,"name":"More Names"},
{"id":5,"name":"Cool Person"}]
}];
Put [ and ]
I have edited my answer, can u please try this
var data = [
"club":
[{"id":1,"name":"This is a team name"}],
"members":
[{"id":2,"name":"Test Name"},{"id":3,"name":"Another Name"},{"id":4,"name":"More Names"},{"id":5,"name":"Cool Person"}]
];
I tried by adding a extra brace around the json data returned from the server and worked
$.post(your_url, null, function (data) {
//add extra braces before binding to the tree
data = $.parseJSON("[" + data + "]");
$('#tree1').tree({
data: data,
autoOpen: true,
dragAndDrop: true
});
});
The following json data works.
var data = [
{
label: 'RT #dna: IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan\'s return http://t.co/PwDniu8sJg',
children: [
{
label: 'IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan\'s return http://t.co/PwDniu8sJg'
}
]
}
];
By the way, what do you want to show exactly in the tree?