This is all using ecmascript 6; Say I have a class
class Hero {
constructor(id,name){
this.id=id;
this.name=name;
}
}
And I want to have create an array of object of that type of class:
var HEROES = [
{ "id": 11, "name": "Mr. Nice" },
{ "id": 12, "name": "Narco" },
{ "id": 13, "name": "Bombasto" },
{ "id": 14, "name": "Celeritas" },
{ "id": 15, "name": "Magneta" },
{ "id": 16, "name": "RubberMan" },
{ "id": 17, "name": "Dynama" },
{ "id": 18, "name": "Dr IQ" },
{ "id": 19, "name": "Magma" },
{ "id": 20, "name": "Tornado" }
];
Is there a way to do this besides manually parsing the array and then doing New Hero() for each element? It would be nice to be able to do something like HEROES[] = hero.jsonExport() and then later var = hero.jsonImport(HEROES[i]). I've been looking around but without using Typescript this doesn't seem particularly easy. Am I missing something easy?
Thanks!
-Eric
Seems strange to want to import from a specific array instance - especially given that the order could change. It would probably be better to export a factory function which creates a new Hero based off the criteria:
class Hero {
constructor(id,name){
this.id=id;
this.name=name;
}
}
const HEROES = [
{ "id": 11, "name": "Mr. Nice" },
{ "id": 12, "name": "Narco" },
{ "id": 13, "name": "Bombasto" },
{ "id": 14, "name": "Celeritas" },
{ "id": 15, "name": "Magneta" },
{ "id": 16, "name": "RubberMan" },
{ "id": 17, "name": "Dynama" },
{ "id": 18, "name": "Dr IQ" },
{ "id": 19, "name": "Magma" },
{ "id": 20, "name": "Tornado" }
];
export default function createHero(index) {
const hero = HEROES[index];
return new Hero(hero.id,hero.name);
}
And the caller:
import createHero from "./hero";
const hero1 = createHero(1);
Related
I have a problem with saving to playersJson String, data from node "players". Node is created based on json dataJson, created with byte[] playesFile. I suspect that the error is due to incorrect parsing of these strings?
As a result, String playersJson returns an empty String and I would like it to contain information about "players" in json format, which I will then throw into Map<String,Player>
Code fragment:
byte[] playersFile = storageService.downloadFile(FILENAME);
String dataJson = new String(playersFile);
try {
JsonNode jsonNode = objectMapper.readTree(dataJson);
String playersJson = jsonNode.get("players").asText();
data = objectMapper.readValue(playersJson, new TypeReference<Map<String, Player>>(){});
} catch (JsonProcessingException e) {
e.printStackTrace();
}
String dataJson:
{
"players":
[
{
"key": "03a2452c-9d6b-47f5-9616-9a6833312762",
"value": {
"uuid": "2ae8d022-e0f4-4502-8e0e-1874997543e3",
"name": "Artur",
"elo": 2000,
"gamesPlayed": 0,
"email": "arti123i#mail.com"
}
},
{
"key": "8526db7c-6930-45bf-9ae1-fb93e97ff4ba",
"value": {
"uuid": "1bb43d73-3f94-40fc-a680-99f4a9304001",
"name": "Kamil",
"elo": 2000,
"gamesPlayed": 0,
"email": "kamil223#mail.com"
}
},
{
"key": "5a65ba8c-2180-464b-afe4-69c29b785282",
"value": {
"uuid": "b3dc8c98-5759-433e-88cd-0233946b9241",
"name": "Marek",
"elo": 3000,
"gamesPlayed": 0,
"email": "marek111#mail.com"
}
}
],
"games":
[
{
"reportedTime": "2022-07-11T14:43:10.0354202+02:00",
"reportedBy": {
"uuid": "2ae8d022-e0f4-4502-8e0e-1874997543e3",
"name": "Artur",
"elo": 2016,
"gamesPlayed": 1,
"email": "arti123i#mail.com"
},
"result": [
[
{
"player": {
"uuid": "2ae8d022-e0f4-4502-8e0e-1874997543e3",
"name": "Artur",
"elo": 2016,
"gamesPlayed": 1,
"email": "arti123i#mail.com"
},
"eloBefore": 2000,
"eloAfter": 2016
},
{
"player": {
"uuid": "1bb43d73-3f94-40fc-a680-99f4a9304001",
"name": "Kamil",
"elo": 2016,
"gamesPlayed": 1,
"email": "kamil223#mail.com"
},
"eloBefore": 2000,
"eloAfter": 2016
}
],
[
{
"player": {
"uuid": "b3dc8c98-5759-433e-88cd-0233946b9241",
"name": "Marek",
"elo": 2968,
"gamesPlayed": 1,
"email": "marek111#mail.com"
},
"eloBefore": 3000,
"eloAfter": 2968
}
]
]
}
]
}
code image
code debugging
i have a question:
Is it possible read a json file and convert to dataframe dynamically?
My example is the next code:
Having this json file, i need 3 table dataframes:
{
"date_time": "01-03-2022, 15:18:32",
"regions": {
"Home Region": "Madrid",
"Primary Region": "Barcelona",
"Secondary Region": "Rio"
},
"customers": [
{
"name": "campo santo",
"address": "rua trebal 1",
"phone": 987456321,
"parking": true
},
{
"name": "santo da silva",
"address": "rua sama 6",
"phone": 654321987,
"parking": false
},
{
"name": "roger campos",
"address": "av casal 10",
"phone": 684426654,
"parking": true
}
],
"office": [
{
"location": "madrid",
"co_working_spaces": 25,
"kitchen": false,
"food_track": 2,
"internal_staff": [
{
"id": 123,
"name": "pablo"
},
{
"id": 874,
"name": "saul"
},
{
"id": 741,
"name": "maria"
}
]
},
{
"location": "rio",
"co_working_spaces": 55,
"kitchen": true,
"food_track": 4,
"internal_staff": [
{
"id": 784,
"name": "raquel"
},
{
"id": 874,
"name": "pedro"
},
{
"id": 145,
"name": "maria"
},
{
"id": 365,
"name": "rocio"
}
]
},
{
"location": "barcelona",
"co_working_spaces": 5,
"kitchen": false,
"food_track": 1,
"internal_staff": [
]
},
{
"location": "la",
"co_working_spaces": 5,
"kitchen": true,
"food_track": 4,
"internal_staff": [
{
"id": 852,
"name": "maria"
},
{
"id": 748,
"name": "sara"
}
]
}
]
}
this is my python code:
import pandas as pd
# from pandas.io.json import json_normalize
import json
with open('offices.json') as f:
dt = json.load(f)
# df = pd.json_normalize(dt)
df1 = pd.json_normalize(dt, 'customers', 'date_time')[['name', 'address', 'phone', 'parking', 'date_time']]
print(df1)
df2 = pd.json_normalize(dt, 'office', 'date_time')[['location', 'co_working_spaces', 'kitchen', 'food_track']]
print(df2)
df3 = pd.json_normalize(dt['office'], 'internal_staff', 'location')
print(df3)
With this code, i got my 3 table dataframes. But i have to know the json structure to create the dataframes.
So is it possible to do it dynamically ?
Regards
I cant figure out how to make this conversion iterating a json.
I have this pojo in my backend:
class Part{
Long id;
String name;
Set<Part> parts = new HashSet<>();
}
Every part can have parts and this part more parts and so on.
I get this parts from httpclient in angular and get this json:
[{
"id": 1,
"name": "Parts A and B",
"parts": [{
"id": 2,
"name": "A",
"parts": [{
"id": 4,
"name": "A1",
"parts": []
}]
},
{
"id": 3,
"name": "B",
"parts": []
}
]
},
{
"id": 2,
"name": "A",
"parts": []
},
{
"id": 3,
"name": "B",
"parts": []
},
{
"id": 4,
"name": "A1",
"parts": []
}
]
And need to convert to this to populate a PrimeNG TreeTable:
{
"data": [{
"data": {
"name": "Parts A and B",
"id": "1"
},
"children": [{
"data": {
"name": "Part A",
"id": "2"
},
"children": [{
"data": {
"name": "A1",
"id": "4"
}
}]
},
{
"data": {
"name": "Part B",
"id": "3"
},
"children": []
}
]
},
{
"data": {
"name": "Part A",
"id": "2"
},
"children": []
},
{
"data": {
"name": "Part B",
"id": "3"
},
"children": []
},
{
"data": {
"name": "A1",
"id": "4"
},
"children": []
}
]
}
How can I do that?
In angular I get this in an array parts: Part[] and need partsTree: TreeNode[]
Thanks!!!
Its just a simple conversion by a map;
interface PartAPI{
id: number;
name: string;
parts : PartAPI[];
}
interface Data {
id: number;
name: string;
}
interface Part {
data : Data;
children : Part[];
}
console.log('a')
let convert = (inputArr: PartAPI[] = []) : Part[] => {
return inputArr.map(partApi => ({ data : { id : partApi.id , name : partApi.name }, children: convert(partApi.parts) }) as Part)
}
let data : PartAPI[] = [{
"id": 1,
"name": "Parts A and B",
"parts": [{
"id": 2,
"name": "A",
"parts": [{
"id": 4,
"name": "A1",
"parts": []
}]
},
{
"id": 3,
"name": "B",
"parts": []
}
]
},
{
"id": 2,
"name": "A",
"parts": []
},
{
"id": 3,
"name": "B",
"parts": []
},
{
"id": 4,
"name": "A1",
"parts": []
}
]
console.log(convert(data));
I'm working on some code in which uses dynamic variables jsonResponse .
dynamic jsonResponse = JsonConvert.DeserializeObject(response);
This variable contains collection of hotel list in json format. From this collection I am getting roomlist collection in a new variable roomResponseList :
var roomResponseList = jsonResponse["hotels"]["hotels"][rooms].roomResponseList;
I am getting first room detail into **JObject responseRateKeys **:
foreach (var roomByResponse in roomResponseList)
{
JObject responseRateKeys = JObject.Parse(roomByResponse.ToString());
var boardNameListByResponse = responseRateKeys.AsJEnumerable().AsEnumerable()
.Select(t => t["rates"]["boardName"].ToString().Trim())
.Distinct()
.ToList();
}
But when I am trying to get any item list from JObject by using linq lambda, I am getting error,
"Cannot access child value on Newtonsoft.Json.Linq.JProperty."
Value of roomByResponse=
{ "code": "DBL.KG-NM", "name": "DOUBLE KING BED NON SMOKING", "rates": [ { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|RO|IWH25|1~1~0||N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NRF", "rateType": "RECHECK", "net": "186.04", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "RO", "boardName": "ROOM ONLY", "cancellationPolicies": [ { "amount": "149.63", "from": "2017-07-14T03:29:00+05:30" } ], "rooms": 1, "adults": 1, "children": 0, "dailyRates": [ { "offset": 1, "dailyNet": "93.02" }, { "offset": 2, "dailyNet": "93.02" } ] }, { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|BB|IWB25|1~1~0||N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NOR", "rateType": "RECHECK", "net": "238.92", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "BB", "boardName": "BED AND BREAKFAST", "rooms": 1, "adults": 1, "children": 0, "dailyRates": [ { "offset": 1, "dailyNet": "119.46" }, { "offset": 2, "dailyNet": "119.46" } ] }, { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|RO|IWH25|2~2~1|2|N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NRF", "rateType": "RECHECK", "net": "372.06", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "RO", "boardName": "ROOM ONLY", "cancellationPolicies": [ { "amount": "299.25", "from": "2017-07-14T03:29:00+05:30" } ], "rooms": 2, "adults": 2, "children": 1, "childrenAges": "2", "dailyRates": [ { "offset": 1, "dailyNet": "186.03" }, { "offset": 2, "dailyNet": "186.03" } ] }, { "rateKey": "20171217|20171219|W|256|237403|DBL.KG-NM|ID_B2B_26|BB|IWB25|2~2~1|2|N#AFF5C93E36054661ADCBC14A78A532AE1007", "rateClass": "NOR", "rateType": "RECHECK", "net": "477.84", "allotment": 99, "paymentType": "AT_WEB", "packaging": false, "boardCode": "BB", "boardName": "BED AND BREAKFAST", "rooms": 2, "adults": 2, "children": 1, "childrenAges": "2", "dailyRates": [ { "offset": 1, "dailyNet": "238.92" }, { "offset": 2, "dailyNet": "238.92" } ] } ] }
Thank you
Pravesh Singh
change linq to
responseRateKeys["rates"].AsJEnumerable().Select(t=>t["boardName"]).Distinct().ToList()
This is the JSON response I am trying to parse:
{
"data": {
"Content": {
"id": 26,
"name": "Dashboard1"
},
"List": [
{
"ListContent": {
"id": 178,
"name": "Card-144"
},
"cards": [
{
"id": 1780,
"configuration": {
"id": 7178,
"name": "Emp"
}
}
]
},
{
"ListContent": {
"id": 179,
"name": "Card-14"
},
"cards": [
{
"id": 1798,
"configuration": {
"id": 1789,
"name": "RandomColumns"
}
}
]
},
{
"ListContent": {
"id": 180,
"name": "Card-1"
},
"cards": [
{
"id": 18080,
"configuration": {
"id": 1080,
"allow": true
}
}
]
},
{
"ListContent": {
"id": 181,
"name": "Card-14"
},
"cards": [
{
"id": 18081,
"configuration": {
"id": 1881,
"name": "Functions"
}
}
]
},
{
"ListContent": {
"id": 182,
"name": "Card-1443"
},
"cards": [
{
"id": 1782,
"configuration": {
"id": 1802,
"name": "Emp-O"
}
}
]
}
]
}
}
From the Json, I need to extract "id"s under the "ListContent" nodes and store it in an array. Also, will need to ignore "id"s under the child nodes.
Here is a groovy script I am trying to achieve this with,
def CList = ""
import groovy.json.JsonSlurper
def jsonRespData = context.expand( '${TestStep#Response#$.data.List}' )
def outputResp = new JsonSlurper().parseText(jsonRespData)
outputResp.id.each()
{log.info( ":"+ it)
CList=CList.concat(it.toString()).concat(',')}
log.info (CList)
So, the array that I am expecting is CList [178,179,180,181,182]
but I am currently getting null.
What should be the correct groovy to only read "id" from "ListContent" and write it to an array?
Any help would be really appreciated.
Thanks in advance.
You can just use the (implicit) spread operator like this:
def json = new groovy.json.JsonSlurper().parse('/tmp/x.json' as File)
//
def i = json.data.List.ListContent.id
assert i == [178, 179, 180, 181, 182]
// with explicit spread operator
def e = json.data.List*.ListContent*.id
assert e == [178, 179, 180, 181, 182]
def str = '''
{
"data": {
"Content": {
"id": 26,
"name": "Dashboard1"
},
"List": [
{
"ListContent": {
"id": 178,
"name": "Card-144"
},
"cards": [
{
"id": 1780,
"configuration": {
"id": 7178,
"name": "Emp"
}
}
]
},
{
"ListContent": {
"id": 179,
"name": "Card-14"
},
"cards": [
{
"id": 1798,
"configuration": {
"id": 1789,
"name": "RandomColumns"
}
}
]
},
{
"ListContent": {
"id": 180,
"name": "Card-1"
},
"cards": [
{
"id": 18080,
"configuration": {
"id": 1080,
"allow": true
}
}
]
},
{
"ListContent": {
"id": 181,
"name": "Card-14"
},
"cards": [
{
"id": 18081,
"configuration": {
"id": 1881,
"name": "Functions"
}
}
]
},
{
"ListContent": {
"id": 182,
"name": "Card-1443"
},
"cards": [
{
"id": 1782,
"configuration": {
"id": 1802,
"name": "Emp-O"
}
}
]
}
]
}
}
'''
def outputResp = new groovy.json.JsonSlurper().parseText(str)
outputResp.data.List.collect { it.ListContent.id }
As you already have List from (context.expand( '${TestStep#Response#$.data.List}' )) , you can simply do:
outputResp.collect { it.ListContent.id }
Above returns an ArrayList.