JSON value search - json

I'm getting below JSON result from a PHP page using ajax request. I tried a lot to get the desired result. I have done below approach but still unable to get as expected.
{
"search": {
"entry": [
{
"attribute": [
{
"name": "title",
"value": [
"Mr."
]
},
{
"name": "mail",
"value": [
"kiran#gmail.com",
"Kiran#yahoo.com",
"kiran#hotmail.com"
]
}
]
}
]
}
}
I have tried the following search to get the value using Defiant.js
success: function (data) {
var xx=JSON.stringify(data);
// var got = $.each(data.search.entry[0].attribute, function (i, v) {
// return v;
//
// });
alert(xx);
var z=JSON.search( xx, '//*[name="title"]/value[1]' );
alert(z);
},
How would I can get results like title='Mr' or mail='kiran#gmail.com'.

Why you need regex solution if your json has proper structure. I have seen your code and json and it seems that you need first index value for title and mail. see following function which can search both title and mail.
var arrt = ' {"search": {"entry": [ {"attribute": [ {"name": "title","value": [ "Mr."] }, {"name": "mail","value": [ "kiran#gmail.com", "Kiran#yahoo.com", "kiran#hotmail.com"] }] }] }}';
SearchMyWordTT(arrt,"title");
//SearchMyWordTT(arrt,"mail");
function SearchMyWordTT(arr,index){
arr = JSON.parse(arr);
for(var i=0;i< arr["search"]["entry"][0]['attribute'].length;i++){
if(typeof (arr["search"]["entry"][0]['attribute'][i]['name']) !="undefined" && arr["search"]["entry"][0]['attribute'][i]['name'] == index)
retIn = arr["search"]["entry"][0]['attribute'][i]['value'][0];
}
return retIn;
}

Related

How to remove objoct from object by finding in type script

This is my object
"filterValue":[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}},
]
from this i want to search where value.Id = 2 and i want to remove that obeject line.
how can i do that..?
note:first value will be empty there is no data in value.
i have tried something like this:
filterValue.splice( filterValue.indexOf(2), 1 );
You can't use indexOf in this case because you are checking a complex object but you can use findIndex like this:
filterValue.splice( filterValue.findIndex(a => a.Id == 2), 1 );
You might want to change the code the check if findIndex actually found something by checking if it returns something larger than (or equal to) 0.
You can use filter to get a new filtered array (filteredArr):
var arr = [
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}}
];
var filteredArr = arr.filter((x) => JSON.stringify(x.value) !== JSON.stringify({"Id":"2"}));
console.log(filteredArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have a couple of subtly traps to avoid with your specific example.
The structure of items differs, so you need to be careful that you don't have a problem with the "--Select a Member--" item, which doesn't have a value.Id.
The example below cheaply solves the type issue (the best common type between the array members doesn't contain the property you are interested in).
const items = [
{ "label": "--Select a Member--", "value": "" },
{ "label": "ghi.jkl", "value": { "Id": "1", } },
{ "label": "abc.def", "value": { "Id": "2", } },
{ "label": "asd.vdf", "value": { "Id": "3", } },
];
const filtered = items.filter((i: any) => !i.value || !i.value.Id || i.value.Id !== '2');
console.log(filtered);
Output:
[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1"}},
{"label":"asd.vdf","value":{"Id":"3"}}
]
const obj = {
filterValue: [
{ label: "--Select a Member--", value: "" },
{ label: "ghi.jkl", value: { Id: "1" } },
{ label: "abc.def", value: { Id: "2" } },
{ label: "asd.vdf", value: { Id: "3" } }
]
};
var changedObj = obj.filterValue.filter((data, index) => {
return data.value.Id != "1";
});
console.log(changedObj);

Use and Convert Array into JSON

I have this array
["123", "456", "789", "0"]
And I would like to build a JSON out of its values.
Expected result is
{
"list": [
{
"code": 123
},
{
"code": 456
},
{
"code": 789
},
{
"code": 0
}
]
}
How do I work this structure in javascript? Thank u for the help
You will have to create a loop and a JS variable that writes it that way then JSON.Stringify it out once complete.... I.e.
var json = { list: [] };
for(i = 0 ; i < arr.length ; i++) {
json.list.push( { code : arr[i] } );
}
var stringOutput = JSON.Stringify(json)
Note: not tried to compile or run the code but that should be close to what you want.
As a one-liner you can do the following:
let result = {"list": ["123", "456", "789", "0"].map((code) => { return {"code":code} })};
Or to break out the steps and to use older syntax:
var orig = ["123", "456", "789", "0"];
var list = orig.map(function(code) {
return {"code": code};
});
var result = {"list": list};

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

Restangular - custom search - search within an array

Lets assume I have an mongodb items collection looking like this (MongoLab):
{
"_id": {
"$oid": "531d8dd2e4b0373ae7e8f505"
},
"tags": [
"node",
"json"
],
"anotherField": "datahere"
}
{
"_id": {
"$oid": "531d8dd2e4b0373ae7e8f505"
},
"tags": [
"ajax",
"json"
],
"anotherField": "datahere"
}
I would like to get all items where a node is within the tags array.
I've tried the below, but no success - it is returning all items - no search performed?
Plunker demo : http://plnkr.co/edit/BYj09TOGyCTFKhhBXpIO?p=preview
// $route.current.params.id = "node" - should give me only 1 record with this tag
Restangular.all("items").customGET("", { "tags": $route.current.params.id });
Full example, return same record for both cases:
var all = db.all('items');
// GET ALL
all.getList().then(function(data) {
$scope.all = data;
console.log(data);
});
// SEARCH for record where "tags" has got "node"
all.customGET('', { "tags": "node"}).then(function(data) {
$scope.search = data;
console.log(data);
});
Any suggestion would be much appreciated.
According to Mongolab REST API Documentation you have to pass the query object with the q parameter. In your case it is q={"tags":"node"}.
Using Restangular it will be like this:
Restangular.all("items").customGET('', { q: {"tags": "node"}})

evaluating json object returned from controller and attaching it to prepopulate attribute of tokeninput

I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}