Es6: Create an array of objects from a json - ecmascript-6

I have a json in the below format.
[
{"id": 1,
"name": "peter" },
{"id": 2,
"name": "john" },
{"id": 3,
"name": "justin" }
.
.
{"id": 500,
"name": "david" },
]
I am trying to create an array in batches of 10 in the below format
[
{
{"id": 1,
"name": "peter" },
.
.
{"id": 10,
"name": "nixon" },
},
{
{"id": 11,
"name": "nancy" },
.
.
{"id": 20,
"name": "underwood" },
}
.
.
]
I tried using reduce and tried for loop to loop through it, but was unsuccessful

Here's a demo.
const str = "abcdefghigklmnopqrstuvwxyz";
let data = [];
for(let i = 0; i < 26; i++){
data.push({id : i, name: str.charAt(i)});
}
let res = data.reduce((acc, d) => {
let groupId = Math.floor(d.id / 10);
acc[groupId] = acc[groupId] || {};
acc[groupId][d.id] = d;
return acc;
}, {});
console.log(Object.values(res));
If you can ensure that id is the same sequence as their position in array, i think simply slice will better.

Related

pandas column to list for a json file

from a Dataframe, I want to have a JSON output file with one key having a list:
Expected output:
[
{
"model": "xx",
"id": 1,
"name": "xyz",
"categories": [1,2],
},
{
...
},
]
What I have:
[
{
"model": "xx",
"id": 1,
"name": "xyz",
"categories": "1,2",
},
{
...
},
]
The actual code is :
df = pd.read_excel('data_threated.xlsx')
result = df.reset_index(drop=True).to_json("output_json.json", orient='records')
parsed = json.dumps(result)
jsonfile = open("output_json.json", 'r')
data = json.load(jsonfile)
How can I achive this easily?
EDIT:
print(df['categories'].unique().tolist())
['1,2,3', 1, nan, '1,2,3,6', 9, 8, 11, 4, 5, 2, '1,2,3,4,5,6,7,8,9']
You can use:
df = pd.read_excel('data_threated.xlsx').reset_index(drop=True)
df['categories'] = df['categories'].apply(lambda x: [int(i) for i in x.split(',')] if isinstance(x, str) else '')
df.to_json('output.json', orient='records', indent=4)
Content of output.json
[
{
"model":"xx",
"id":1,
"name":"xyz",
"categories":[
1,
2
]
}
]
Note you can also use:
df['categories'] = pd.eval(df['categories'])

how to group result with json key name in laravel

user table
id name age
1 TuTu 3
2 SuSu 4
3 YuYu 4
4 MoMo 4
I want to output json like this.
[
{
"age": 3,
"user": [
{
"id": 2,
"name": "TuTu"
}
]
},
{
"age": 4,
"user": [
{
"id": 2,
"name": "SuSu"
},
{
"id": 3,
"name": "YuYu"
},
{
"id": 4,
"name": "MoMo"
}
]
}
]
User::get()->groupBy("age") not working expected.
How could add json key age and user like above format in laravel?
The answer gives you the desired output, however consider using an API Resource for JSON Response.
$response = [];
User::get()->groupBy('age')->each(function ($item, $key) use (&$response) {
$temp = [];
$temp['age'] = $key;
$temp['user'] = $item->transform(function ($i, $k) {
unset($i['age']);
return $i;
})->all();
$response[] = $temp;
});
var_dump($response); // Your Output JSON

merge lists of dictionaries in terraform v0.12

I would like to do the following using terraform:
I have 2 JSONs:
1.json:
[
{
"description": "description1",
"url": "url1",
"data": "data1"
},
{
"description": "description2",
"url": "url2",
"data": "data2",
"action": "action2"
},
{
"description": "description3",
"url": "url3",
"data": "data3"
}
]
2.json:
[
{
"description": "description1",
"url": "url1",
"data": "data1"
},
{
"description": "description2_new",
"url": "url2",
"data": "data2_new"
},
{
"description": "description4",
"url": "url4",
"data": "data4"
}
]
and I want to merge them into one. Dictionaries from the second JSON should override dictionaries from the first one if url key is the same. I.e. combined JSON should look like:
[
{
"description": "description1",
"url": "url1",
"data": "data1"
},
{
"description": "description2_new",
"url": "url2",
"data": "data2_new"
},
{
"description": "description3",
"url": "url3",
"data": "data3"
},
{
"description": "description4",
"url": "url4",
"data": "data4"
}
]
Using python I can easily do it:
import json
with open('1.json') as f:
json1 = json.load(f)
with open('2.json') as f:
json2 = json.load(f)
def list_to_dict(json_list):
res_dict = {}
for d in json_list:
res_dict[d['url']] = d
return res_dict
def merge_json(json1, json2):
j1 = list_to_dict(json1)
j2 = list_to_dict(json2)
j1.update(j2)
res_list = []
for key in j1.keys():
res_list.append(j1[key])
return res_list
print(json.dumps(merge_json(json1, json2), indent=4))
How can I do that using terraform?
Using terraform 0.12.x
$ cat main.tf
locals {
# read from files and turn into json
list1 = jsondecode(file("1.json"))
list2 = jsondecode(file("2.json"))
# iterate over lists and turn url into a unique key
dict1 = { for item in local.list1 : item.url => item }
dict2 = { for item in local.list2 : item.url => item }
# combine both dictionaries so values converge
# only take its values
merged = values(merge(local.dict1, local.dict2))
}
output "this" {
value = local.merged
}
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
Outputs:
this = [
{
"data" = "data1"
"description" = "description1"
"url" = "url1"
},
{
"data" = "data2_new"
"description" = "description2_new"
"url" = "url2"
},
{
"data" = "data3"
"description" = "description3"
"url" = "url3"
},
{
"data" = "data4"
"description" = "description4"
"url" = "url4"
},
]
Terraform supports expanding a list into function parameters using the ... operator. This will allow an arbitrary number of documents to be read.
(I'm not sure, but I believe this feature was added in v0.15)
For this example, I added a new file 3.json with the contents:
[
{
"description": "description4_new",
"url": "url4",
"data": "data4_new"
}
]
For main.tf, I'm using the same logic as #someguyonacomputer's answer:
$ cat main.tf
locals {
jsondocs = [
for filename in fileset(path.module, "*.json") : jsondecode(file(filename))
]
as_dicts = [
for arr in local.jsondocs : {
for obj in arr : obj.url => obj
}
]
# This is where the '...' operator is used
merged = merge(local.as_dicts...)
}
output "as_list" {
value = values(local.merged)
}
Result:
Changes to Outputs:
+ as_list = [
+ {
+ data = "data1"
+ description = "description1"
+ url = "url1"
},
+ {
+ data = "data2_new"
+ description = "description2_new"
+ url = "url2"
},
+ {
+ data = "data3"
+ description = "description3"
+ url = "url3"
},
+ {
+ data = "data4_new"
+ description = "description4_new"
+ url = "url4"
},
]
References:
Terraform Docs -- Function Calls # Expanding Function Arguments

underscore.js how to get an element from a JSON object using _.filter

I have the following JSOn object ( Array of elements )
var roles = [
{
"label": "alpha",
"children": [
{"label": "role1","title": "role1","value": "1"},
{"label": "role2","title": "role2","value": "2"}
]
},
{
"label": "beta",
"children": [
{"label": "role3","title": "role3","value": "3"},
{"label": "role4","title": "role4","value": "4"}
]
},
{
"label": "delta",
"children": [
{"label": "role5","title": "role5","value": "5"},
{"label": "role6","title": "role6","value": "6"}
]
}
]
I am trying to get ( and later remove.. ) an element with a specific label
I defined a where object
var where = {key: 'label', value:"alpha"};
and I filter the object :
var filteredRoles = _.filter(roles, function (el) {
return el[where.key] && _.isArray(el[where.key]) &&
_.indexOf(el[where.key], where.value) >= 0;
});
console.log("found "+JSON.stringify(filteredRoles, null, 2));
but I cannot get it : found = []
where am I wrong ?
thanks for feedback
try this
var result = _.filter(roles, function(role) {
return (role[where.key] === where.value) && _.isArray(role['children']);
})
here is a working plunk

How to convert JSON Array in JSON Object

I have a JSON Array in below format which I want to convert to JSON Object in (key,value) pair.
Since I am new to JSON I don't know how to achieve this.
{
"id": [
"100",
"101",
"102"
],
"Name": [
"ajit",
"amol",
"kiran"
],
"sex": [
"Male",
"Male",
"Male"
]
}
I want to convert above in the format like
[
{
"id": "100",
"Name": "ajit",
"Sex": "Male"
},
{
"id": "101",
"Name": "amol",
"Sex": "Male"
},
{
"id": "102",
"Name": "kiran",
"Sex": "Male"
}
]
Can you guys share your valuable thoughts on how to do this please?
Ajit
Assuming lots of things this works for the example,
var arrayOfObjects = [] ;
/**
* #params Object obj formated like the first one
*/
var i = 0,
arrayOfObjects = [] ;
for( prop in obj ) {
if ( prop instanceof Array ) {
for( i = 0 ; i < obj[prop].length ; ++i ) {
if ( typeof arrayOfObjects[i] !== undefined ) {
arrayOfObjects[i][prop] = obj[prop][i] ;
} else {
var newObj = {} ;
newObj[prop] = obj[prop][i] ;
arrayOfObjects.push(newObj) ;
}
}
}
}