AngularJS - parsing JSON feed with namespace - javascript

New to angular, and it is awesome.
One thing I am having a brain fart on is parsing a JSON feed that contains namespaces:
Example from JSON feed:
"title": {
"label": "Fuse"
},
"im:name": {
"label": "John Doe"
},
"im:image": [ {
"label": "70x70",
"attributes": {
"height": "55"
}
}, {
"label": "80x80",
"attributes": {
"height": "60",
"im:link": "www.google.com"
}
}, {
"label": "90x90",
"attributes": {
"height": "170"m
"im:link": "www.yahoo.com"
}
}],
I can successfully parse items without namespaces fine like so:
<p ng-repeat="item in results.feed['entry']">
title: {{item.title['label']}}
</p>
But cannot get the items with namespaces to display using:
name: {{item.['im:name']['label']}}
OR
name: {{item.['im-name']['label']}}
OR
name: {{item.['im->name']['label']}}
Since being a newbie, I thought something like this would work:
<div xmlns:im="http://www.aol.com" id="im-app" im-app="im">
<p ng-repeat="item in results.feed['entry']">
…namespace code in here…
</p>
</div>
But that did not help.
Extra bonus question: What if a namespace contains attributes, that also contain namespaces?
Any help would greatly be appreciated.
Thanks!
Roc.
Although Craig answered the question,
This is also for reference for others:
If you want to target a specific key inside of an object set:
"im:image":[
{
"label":google",
"attributes":{
"height":"55"
}
},
{
"label":"yahoo",
"attributes":{
"height":"60"
}
},
{
"label":"aol",
"attributes":{
"height":"170"
}
}
{{item['im:image'][2]['label']}}
Will get the 3rd key in that set.
Thanks.

Get rid of the dot after item
Working example: http://jsfiddle.net/bonza_labs/Kc2uk/
You access the properties exactly the same way as straight javascript (because angular is basically eval()-ing the expression as javascript**). item.['foo'] is not valid javascript. You are correct in using square-bracket notation as my:name is not valid for dot-notation.
valid:
item.foo
item['foo']
with non-standard property names:
item['foo:bar']
item['foo-bar']
and in your case:
{{item['im:name']['label']}}
** or close enough for understanding this solution

Related

How to search for specific word and exact match in ElasticSearch

sample data for title
actiontype test
booleanTest
test-demo
test_demo
Test new account object
sync accounts data test
default Mapping for title
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
tried with this query search
{
"query": {
"bool": {
"must": [
{
"match": {
"title": "test"
}
}
]
}
},
}
here my expectation
with specific word(e.g. : test ) it should return following titles
expect
actiontype test
booleanTest
test-demo
test_demo
Test new account object
sync accounts data test
But
got
actiontype test
test-demo
test_demo
Test new account object
sync accounts data test
With exact match (e.g. : sync accounts data test ) it should return only this(sync accounts data test) but got all records those contains this words (sync,account,data,test).
What should I do to make this happen ? Thanks.
I am not sure which ES version you're using but the following should give you an idea.
Using your mapping you can get all title text with test, including booleanTest using query string query type. Eg.
GET {index-name}/{mapping}/_search
{
"query": {
"query_string": {
"default_field": "title",
"query": "*test*"
}
}
}
However, for this to work, make sure you give your title field an analyzer with a lowercase analyzer filter (see below settings example). Your current mapping will not work since it's just pure text as is... test /= TEST by default.
There are other ways, if you're interested to know the workings of ES... Eg. You can also match booleanTest in your match query by writing a custom nGram filter to your index settings. Something like,
{
"index": {
"settings": {
"index": {
"analysis": {
"filter": {
"nGram": {
"type": "nGram",
"min_gram": "2",
"max_gram": "20"
}
},
"ngram_analyzer": {
"filter": [
"lowercase",
"nGram"
],
"type": "custom",
"tokenizer": "standard"
}
}
}
}
}
}
NB: ngram_analyzer is just a name. You can call it whatever.
min_gram & max_gram: Pick numbers that work for you.
Learn more about n-gram filter, the goods and bad here: N-GRAM
Then you can add the analyzer to your field mapping like,
{
"title": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256,
"analyzer": "ngram_analyzer"
}
}
}
}
Lastly for exact matches, these work on type keyword. So based on your mapping, you already have the keyword field so you can use term query to get the exact match by searching on the title.keyword field;
GET {index-name}/{mapping}/_search
{
"query": {
"term": {
"title.keyword": {
"value": "sync accounts data test"
}
}
}
}
Also, you will want to read/ learn more about these solutions and decide on the best solution based on your indexing setup and needs. Also, there may be more ways to achieve what you need, this should be a good start.

Mongoose how do we update nested objects

I am trying to update nested object using mongoose. I am trying to update the "remindTime date" only and keep the "time" I can update the "remindTime date" however it erases my "remindTime time" property.
I have try the following and none of them work
Model.updateMany(req.query, { remindTime: { date: "2021-09-28" } })
Model.updateMany(req.query, { remindTime: $set:{ { date: "2021-09-28" } } } )
Database data that I am updating
{
"_id": {
"$oid": "614d3cedfb2600340fdb28f9"
},
"date": "2021-09-23",
"title": "First test",
"description": "not working yet",
"remindTime": {
"date": "2021-09-28",
"time": "01:20 am"
},
"isComplete": false,
}
Please try this:
Model.updateMany(req.query, { "remindTime.date": "2021-09-28"})
You can use dot notation:
According to docs:
MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.
To specify or access a field of an embedded document with dot notation, concatenate the embedded document name with the dot (.) and the field name, and enclose in quotes:
"<embedded document>.<field>"
So the query:
Model.updateMany(req.query,
{
"$set": {
"remindTime.date": "new date"
}
})
Example here

Extracting only portion of JSON document with REST API search call in MarkLogic

I am looking out methods of Extracting only portion of JSON document with REST API search call in MarkLogic using JavaScript or XQuery.
I have tried using query options of re extract-document-data but was not successful. Tried checking my extract path using CTS.validextract path but that function was not recognised in Marklogic 9.0-1
Do I have to using specific search options like constraints or structured query.
Could you please help out? TIA.
I have below such sample document
{
"GenreType": {
"Name": "GenreType",
"LongName": "Genre Complex",
"AttributeDataType": "String",
"GenreType Instance Record": [
{
"Name": "GenreType Instance Record",
"Action": "NoChange",
"TitleGenre": [
"Test1"
],
"GenreL": [
"Test1"
],
"GenreSource": [
"ABC"
],
"GenreT": [
"Test1"
]
},
{
"Name": "GenreType Instance Record",
"Action": "NoChange",
"TitleGenre": [
"Test2"
],
"GenreL": [
"Test2"
],
"GenreSource": [
"PQR"
],
"GenreT": [
"Test2"
]
}
]
}
}
in which i need to search a document with attribute "TitleGenre" WHERE GenreSource = “ABC” in the GenreType complex attribute. It's an array in json document.
I was using the search option as below, (writing search option in XML, but searching the in json documents)
<extract-path>/GenreType/"GenreType Instance Record"[#GenreSource="ABC"]</extract-path>
I am still facing the issues. If possible could you please let me know how json documents can be searched for such specific requirement? #Wagner Michael
You can extract document data by using the extract-document-data option.
xquery version "1.0-ml";
let $doc := object-node {
"GenreType": object-node {
"Name": "GenreType",
"LongName": "Genre Complex",
"AttributeDataType": "String",
"GenreType-Instance-Record": array-node {
object-node {
"TitleGenre": array-node {
"Test1"
},
"GenreSource": array-node {
"ABC"
}
},
object-node {
"TitleGenre": array-node {
"Test2"
},
"GenreSource": array-node {
"PQR"
}
}}
}
}
return xdmp:document-insert("test.xml", $doc);
import module namespace search = "http://marklogic.com/appservices/search"
at "/MarkLogic/appservices/search/search.xqy";
search:search(
"Genre Complex",
<options xmlns="http://marklogic.com/appservices/search">
<extract-document-data>
<extract-path>/GenreType/GenreType-Instance-Record[GenreSource = "ABC"]</extract-path>
</extract-document-data>
</options>
)
In this case /GenreType/GenreType-Instance-Record is the xpath to the extracted element.
Relating to your comment, i also added a predicate [GenreSource = "ABC"]. This way only GenreType-Instance-Record which have a GenreSource of "ABC" are being extracted!
Result:
....
<search:extracted kind="array">[{"GenreType-Instance-Record":{"TitleGenre":["Test1"], "GenreSource":["ABC"]}}]
</search:extracted>
....
Note:
You can add multiple <search:extract-path> elements!
I had to change the name of GenreType Instance Record to GenreType-Instance-Record. I am not sure if you can have property names with whitespaces and access them with xpath. I couldn't get it working this way.
Please post your search options, if this does not work for you.
Edit: Added a predicate to the extract-path.
Thank you so much Wagner, for your prompt trials. Helped me look out for accurate solution to my problem as of now. I have used below extract path, as i could not modify the names in documents. /GenreType/array-node("GenreType Instance Record")/object-node()/TitleGenre[following-sibling::GenreSource="ABC"]

Correct render of js object with nodejs express

I have some structure that I want to render to my JADE page, so I decided to make JSON-like object to render some kind of data (variables, text, js objects), this JSON object looks like :
var dataSet1 = {
meta: {
"name": "Some text",
"minimum": mini_2,
"maximum": maxi_2,
"currentValue": last_data_2
},
data: {
"values": dataTwo,
"corridor": {
"x1": xc,
"x2": yc2,
"yw": yw2
}
}
};
My render line:
res.render('index', {
data_to_draw: JSON.stringify(dataSet1)
});
Then I`m using this rendered data on my JADE:
displayGraphExampleOne("#graph",
!{data_to_draw.data.values},
!{data_to_draw.meta.currentValue},
!{data_to_draw.meta.minimum},
!{data_to_draw.meta.maximum},
!{data_to_draw.meta.name},
!{data_to_draw.data.corridor.x1},
!{data_to_draw.data.corridor.x2},
!{data_to_draw.data.corridor.yw2});
Cannot read property 'values' of undefined
Im getting such type of error.
Im new with JS , so Im trying to decide what i`m doing wrong. If I will pass data not in js object - it works well, but i need such type of passing data.
thanx
Don't JSON.stringify the object, instead pass the object itself, otherwise you are trying to access the properties of a string, which obviously don't exist.
Just need to format code like this:
var dataSet1= [
{
"meta": {
"name": "Veocity variance",
"minimum": mini_1,
"maximum": maxi_1,
"currentValue": last_data_1
},
"data": {
"values": dataOne,
"corridor": {
"x1": xc,
"x2": yc1,
"yw": yw1
}
}
}
];
And use such call:
displayGraphExampleOne("#graph",
!{first_set}[0][0].data.values,
!{first_set}[0][0].meta.currentValue,
!{first_set}[0][0].meta.minimum,
!{first_set}[0][0].meta.maximum,
!{first_set}[0][0].meta.name,
!{first_set}[0][0].data.corridor.x1,
!{first_set}[0][0].data.corridor.x2,
!{first_set}[0][0].data.corridor.yw);
But not forget to render:
res.render('index', {
first_set: JSON.stringify([dataSet1, dataSet2, dataSet3]),
second_set: JSON.stringify([dataSet1, dataSet2, dataSet3]),
third_set: JSON.stringify([dataSet1, dataSet2, dataSet3])
});

Getting undefined when trying to acces a JSON item [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
i am trying to get a JSON and access its objects to retrieve data, all my paths seems to be working good but one specifically is not working. I just checked and the path is the same the other objects i am trying to access, in the console i keep getting undefined as a result. i will appreciate if you guys could tell me whats wrong with the code i will leave you the JSON structure and also the java Scripti hope you guys can help me figuring out, and also would be good if you could give me some tips on my coding because I am learning.
Java Script:
This function is called when you click on some item in a list.
function checkUser(){
console.log("clicked");
var user = $(this).html();
$.getJSON("js/options.json", function(json){
var itemsLength = json.chat.OnlineContacts.length;
for ( var i = 0; i < itemsLength; i++) {
var jsonUserName = json.chat.OnlineContacts[i].name;
var jsonUserStatus = json.chat.OnlineContacts[i].status;
var jsonUserAvatar = json.chat.OnlineContacts[i].avatar;
if(user == jsonUserName){
/*displayChatWindow(jsonUserName, jsonUserStatus, jsonUserAvatar);*/
console.log(jsonUserAvatar);
}
};
});
}
function displayChatWindow(user, status, avatar){
/*var template = _.template($("#windowTemplate").html(), {userName: user, userStatus: status, userAvatar: avatar});
$("body").prepend(template);*/
$(".messages-container").slimScroll({
height: '200',
size: '10px',
position: 'right',
color: '#535a61',
alwaysVisible: false,
distance: '0',
railVisible: true,
railColor: '#222',
railOpacity: 0.3,
wheelStep: 10,
disableFadeOut: false,
start: "bottom"
});
}
And this is the JSON:
{
"chat": {
"NumberOfOnlineContacts": "7",
"NumberOfOfflineContacts": "800",
"OnlineContacts": [
{
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
},
{
"name": "Catherine Varela",
"status": "Busy",
"avatar": "img/profile-picture3.jpg"
},
{
"name": "Jhonnatan Gonzalez",
"status": "online",
"avatar": "img/profile-picture4.jpg"
},
{
"name": "Juan Prieto",
"status": "away",
"avatar": "img/profile-picture5.jpg"
},
{
"name": "Alexander Barranco",
"status": "Busy",
"avatar": "img/profile-picture6.jpg"
}
],
"OfflineContacts": [
{
"name": "Nandy Torres"
},
{
"name": "Catherine Varela"
},
{
"name": "Jhonnatan Gonzalez"
},
{
"name": "Juan Prieto"
},
{
"name": "Jhonathan Sanchez"
}
]
}
}
When I try to do the console log on avatar like is in the example I just get undefined, but if i do console.log of name or status y just get the correct values.
Consider restructuring the original JSON object so you can access users directly by their unique id - in this case it appears to be "name".
For example:
{
"chat": {
"NumberOfOnlineContacts": "7",
"NumberOfOfflineContacts": "800",
"OnlineContacts": [
{
"Nandy Torres" : {
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
},
{
"Catherine Varela" : {
"status": "Busy",
"avatar": "img/profile-picture3.jpg"
}
},
{...}
]
}
}
This could be accessed in the following ways without the expense of a loop:
json.chat.OnlineContacts[0].avatar
json.chat.OnlineContacts["Nandy Torres"].avatar
json.chat.OnlineContacts[user].avatar
There's an obvious cost-benefit here, but you may get the best of both by inlcuding the "name" attr as well:
"Nandy Torres" : {
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
And eventually moving to a more formal unique id:
"123abc" : {
"name": "Nandy Torres",
"status": "online",
"avatar": "img/profile-picture2.jpg"
}
There's lots of excellent ideas for structuring JSON at json.com
Jhonnatan, I'm glad you got your code working. So this isn't really an "answer" to your original question. But you also asked for tips on the coding and how to improve it. That's great that you're looking for ways to improve your code!
Here's one suggestion for you, a simpler way to write the checkUser() function. This is just a direct conversion of your function that should work with the same data format.
function checkUser() {
console.log( "clicked" );
var user = $(this).html();
$.getJSON( "js/options.json", function( json ) {
$.each( json.chat.OnlineContacts, function( i, contact ) {
if( user == contact.name ) {
displayChatWindow( contact.name, contact.status, contact.avatar );
console.log( contact.avatar );
}
});
});
}
Note how the use of the contact object makes it unnecessary to create all those jsonUserXxxx variables, because code like contact.avatar is just as simple and clear as jsonUserAvatar.
I also highly recommend #DaveRomero's excellent answer for a more strategic look at the question of how best to structure your JSON data.
More related reading: this discussion of JSON restructuring that I posted in response to this question earlier today.

Categories