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};
Related
I have a Json array.
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
Here I want to get the count of total number of customer. I am getting it like this:
json.user.value.length;
And the output is 3. But the thing is I have to avoid duplicate customer number.
As here "1234" is there 2 times. So my output should be 2
How to do this using Typescript.
Use lodash:
var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniqueCustomer.length
Here is link which shows How to use lodash in your app.
You can use Array.reduce to count the unique customers.
const data = {
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
};
function getCustomerCount(arr) {
let tmp = [];
return arr.reduce((acc, curr) => {
if(!tmp.includes(curr.customerNo)) {
return tmp.push(curr.customerNo);
}
return acc;
}, 0);
}
let customers = data.user.value;
let customerCount = getCustomerCount(customers);
console.log(customerCount);
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;
}
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;
i need to convert json tree to table, and back(same table to json tree), PostgreSQL
example:
{
"id": 1,
"title": "Example Node(UnDeleteable, and no counted)",
"items": [
{
"id": 2,
"title": "dfsdfs",
"items": [
{
"id": 3,
"title": "dfsfddfsfd",
"items": [
{
"id": 4,
"title": "dsffdsdfsfdsdfs",
"items": [
{
"id": 5,
"title": "dfsdsfdfsddfs",
"items": []
}
]
}
]
}
]
}
]
}
]
need to be:
ParentId ChildId title
NULL 1 "Example Node(UnDeleteable, and no counted)"
1 2 "dfsdfs"
2 3 "dfsfddfsfd"
etc
....
...
...
someone can help me with that? Thanks!
I think all you need is a two-dimensional array and recursion.
here is my code about tanslating a json to a tree. I think it is easy to feed your needs with a little modification.
var jsonTreeServ = {};
jsonTreeServ.toTreeJson = function (jsonObj, treeArr) {
for (var k in jsonObj) {
var val = jsonObj[k];
if (val instanceof Object) {
var node = {};
node.title = k;
node.value = '';
node.visible = true;
node.nodes = [];
treeArr.push(node);
jsonTreeServ.toTreeJson(val, node.nodes);
} else {
var node = {};
node.title = k;
if(null!==val && ''!==val){
node.title += '=';
val = jsonTreeServ.translateTimestamp(node.title, val);
}
node.value = val;
node.visible = true;
treeArr.push(node);
}
}
return treeArr;
}
I am looking for a JSONPath expression that returns all zone objects with zoneType "big".
Input JSON:
{
"board" : {
"zones" : {
"1": {
"zoneID": 1,
"zoneType":"big"
},
"2": {
"zoneID": 2,
"zoneType":"small"
},
"3": {
"zoneID": 3,
"zoneType":"small"
},
"4": {
"zoneID": 4,
"zoneType":"big"
},
}
}
}
Expected Output:
[{
"zoneID": 1,
"zoneType":"big"
},
{
"zoneID": 4,
"zoneType":"big"
}]
I have tried:
$..zones.[?(#.zoneType='big')]
$..zones.*[?(#.zoneType='big')]
and many others but no luck.
i too initially used jsonpath then later got stuck with some problem so decided to use
looping through the data.so can you try with the below piece of code.
var json = ur json data;
var output = (function (data) {
var keys = (function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
})(data["board"]["zones"]);
var categoryFilter = new Function('data,keys',
"obj=[];" +
"for(var i=0;i<keys.length;i++){" +
"if (data[keys[i]].zoneType == 'big') {" +
"obj.push(data[keys[i]]);" +
"}" +
"}" +
"return obj;"
);
return JSON.stringify(categoryFilter(data["board"]["zones"], keys));
})(json);
Answer should be: $..zones[?(#.zoneType=="big")]
Following works :-
JsonPath.on(json_hash, '$..zones[?(#.zoneType=="big")]')
returns:-
[{"zoneID"=>1, "zoneType"=>"big"}, {"zoneID"=>4, "zoneType"=>"big"}]
JSONPath is unstandardised "query language" but XPath is. Using DefiantJS, you can query JSON structure with XPath expressions. This library extends the global object JSON with the method "search" and it returns matches as an array like object.
Below is example code (and here is the fiddle http://jsfiddle.net/hbi99/DQ9CJ/):
var data = {
"board": {
"zones": {
"1": {
"zoneID": 1,
"zoneType": "big"
},
"2": {
"zoneID": 2,
"zoneType": "small"
},
"3": {
"zoneID": 3,
"zoneType": "small"
},
"4": {
"zoneID": 4,
"zoneType": "big"
}
}
}
},
found = JSON.search(data, '//*[zoneType="big"]'),
str = '';
for (var i=0; i<found.length; i++) {
str += found[i].zoneID +'<br/>';
}
document.getElementById('output').innerHTML = str;