I am trying to load my data/data.json file to my component so that I can display the data when a particular part is clicked.
Snippet of my data
"colors": [
{"id": 1, "type": "direct", "primary": "red", "hex": [1, 4]},
{"id": 2, "type": "direct", "primary": "yellow", "hex": [2, 5]},
{"id": 3, "type": "direct", "primary": "blue", "hex": [3, 6]},
{"id": 4, "type": "split", "primary": "red", "hex": [1, 7, 8]},
{"id": 5, "type": "split", "primary": "yellow", "hex": [2, 9, 10]},
{"id": 6, "type": "split", "primary": "blue", "hex": [3, 11, 12]},
{"id": 7, "type": "analogous", "primary": "red", "hex": [1, 13, 14]},
{"id": 8, "type": "analogous", "primary": "yellow", "hex": [2, 15, 16]},
{"id": 9, "type": "analogous", "primary": "blue", "hex": [3, 17, 18]}
]
I have a another data set that is connected to the hex data that's why they are just numbered
For the loading in the data, I have it as follows:
var app = new Vue({
el:"#app",
data:function() {
return{
json: null
}
},
methods: {
}
});
$.getJSON('data/data.json', function (json) {
app.json = json;
});
What is a good way to add it to my components so that I can properly display what data I am wanting to show?
You could load it within the component itself once it's mounted, using the mounted hook:
// ...
data () {
return { json: null }
},
mounted () {
$.getJSON('data/data.json', json => {
this.json = json
})
}
Related
i am new to python and json. I have this issue where i am unable to get the values of 'labels' print out. It is under a nested dictionary 'result' .
Code that i have tried
for i in data['result']:
print("Value:", i['value'])
values = i['value']
print("X:", values['x'])
print("Y:", values['y'])
print("Width:", values['width'])
print("Height:", values['height'])
Output from the above code
However when i try to do print("labels:", values['labels'])
it return a keyerror: 'labels'
for item in values:
print(item)
this is the output shown
x
y
width
height
rotation
x
y
width
height
rotation
labels
May i ask how do i go out to print out the 'labels' value?
The json files is as follows:
{
"id": 9,
"created_username": "",
"created_ago": "3\u00a0weeks, 3\u00a0days",
"completed_by": {
"id": 1,
"first_name": "",
"last_name": "",
"email": ""
},
"task": {
"id": 1,
"data": {
"image": "/data/upload/2/adf8540d-2-33.png"
},
"meta": {},
"created_at": "2022-11-21T14:52:22.478537Z",
"updated_at": "2022-11-22T12:51:18.105745Z",
"is_labeled": true,
"overlap": 1,
"inner_id": 1,
"total_annotations": 1,
"cancelled_annotations": 0,
"total_predictions": 0,
"comment_count": 0,
"unresolved_comment_count": 0,
"last_comment_updated_at": null,
"project": 2,
"updated_by": 1,
"file_upload": 70,
"comment_authors": []
},
"result": [
{
"original_width": 512,
"original_height": 512,
"image_rotation": 0,
"value": {
"x": 50.898958419872464,
"y": 44.0069438675168,
"width": 2.397222452993284,
"height": 2.0975696463691196,
"rotation": 0
},
"id": "pgaiV8NjWC",
"from_name": "rect",
"to_name": "image",
"type": "rectangle",
"origin": "manual"
},
{
"original_width": 512,
"original_height": 512,
"image_rotation": 0,
"value": {
"x": 50.898958419872464,
"y": 44.0069438675168,
"width": 2.397222452993284,
"height": 2.0975696463691196,
"rotation": 0,
"labels" [
"LM"*
]
},
"id": "pgaiV8NjWC",
"from_name": "labels",
"to_name": "image",
"type": "labels",
"origin": "manual"
}
],
"was_cancelled": false,
"ground_truth": false,
"created_at": "2022-11-22T12:51:18.001777Z",
"updated_at": "2022-11-22T12:51:18.001777Z",
"lead_time": 21.556,
"project": 2,
"parent_prediction": null,
"parent_annotation": null
}
Use the json module
import json
dict = json.load(json_filename)
Then you should access the values by the dictionary keys. Be aware that the result value is a list. Therefore the index 1 is necessary.
values = dict['result'][1]['value']
print("X:", values['x'])
Having following json file
{
"front_page": {
"institue": {
"inst_name": "University Name",
"size": 12,
"type": "bold"
},
"doc_type": {
"name": "(Scope Document)",
"size": 12,
"type": "bold"
},
"project_title": {
"name": "Project Title",
"size": 12,
"type": "bold"
},
"Version": {
"Version": "Version 1.0",
"size": 12,
"type": "bold"
},
"Degree": {
"name": "Becholar of Science in Computer Science(2016-2020)",
"size": 12,
"type": "bold"
}
}
}
I need to get all nested dictionaries as separate dict object.
So far I only managed to get all key, value pairs
def parse_json_obj(json_obj):
for k, v in json_obj.items():
if isinstance(v, dict):
print('found at ', k)
parse_json_obj(v)
else:
print(v)
what I'm trying to do is get each dict and append its content to a pdf page. I've already figured out how to handle each dict for pdf but don't know how to extract dictionaries.
Any help would be appreciated.
Assuming if what you want is all the dicts which dont have sub dicts in them you could do the following.
jdict = {
"front_page": {
"institue": {
"inst_name": "University Name",
"size": 12,
"type": "bold"
},
"doc_type": {
"name": "(Scope Document)",
"size": 12,
"type": "bold"
},
"project_title": {
"name": "Project Title",
"size": 12,
"type": "bold"
},
"Version": {
"Version": "Version 1.0",
"size": 12,
"type": "bold"
},
"Degree": {
"name": "Becholar of Science in Computer Science(2016-2020)",
"size": 12,
"type": "bold"
}
}
}
def parse_json_obj(json_obj):
list_of_dicts = []
for item in json_obj.values():
if isinstance(item, dict):
has_sub_dict = [subdict for subdict in item.values() if isinstance(subdict, dict)]
if has_sub_dict:
list_of_dicts += parse_json_obj(item)
else:
list_of_dicts.append(item)
return list_of_dicts
list_of_dicts = parse_json_obj(jdict)
print(*list_of_dicts, sep="\n")
OUTPUT
{'inst_name': 'University Name', 'size': 12, 'type': 'bold'}
{'name': '(Scope Document)', 'size': 12, 'type': 'bold'}
{'name': 'Project Title', 'size': 12, 'type': 'bold'}
{'Version': 'Version 1.0', 'size': 12, 'type': 'bold'}
{'name': 'Becholar of Science in Computer Science(2016-2020)', 'size': 12, 'type': 'bold'}
If this isnt what you were trying to achieve then i would suggest to update the question to make it more clear.
I have the following json file I am importing into my component:
import { beer, wine, spririts, alcopop } from '../../config/calculator.json';
How can I use the json in my render?
Depending upon what was chosen I would like to use the data for each element, if user clicks beer, then show data for beer. For example, how would I loop through 'sizes' in 'beer'? This is my code so far:
{[drinkType].sizes.map((option, i) =>
<div value={option.id} key={i}>
{option}
</div>
)}
I would like to display the size name, pint, bottle, can etc
I get the error: Cannot read property 'map' of undefined
//calculator.json
{
"beer": {
"name": "Beer or cider",
"sizes": {
"568": {
"name": "Pint",
"size": 0.568,
"id": "pint",
"max": 10,
"icon": "beer_pint"
},
"440": {
"name": "Can",
"size": 0.44,
"id": "can",
"max": 10,
"icon": "beer_can"
},
"330": {
"name": "Bottle",
"size": "0.33",
"id": "bottle",
"max": "10",
"icon": "beer_bottle_330"
},
"275": {
"name": "Small bottle",
"size": 0.275,
"id": "smallBottle",
"max": 10,
"icon": "beer_bottle_275"
}
},
"strength": [4, 4.5, 5, 6, 7, 8, 9]
},
"wine": {
"name": "Wine or champagne",
"sizes": {
"125": {
"name": "Small glass",
"size": 0.125,
"id": "small",
"max": 10,
"icon": "wine_small_glass"
},
"175": {
"name": "Standard glass",
"size": 0.175,
"id": "std",
"max": 10,
"icon": "wine_standard_glass"
},
"250": {
"name": "Large glass",
"size": 0.25,
"id": "large",
"max": 10,
"icon": "wine_large_glass"
},
"1000": {
"name": "Bottle",
"size": 1,
"id": "bottle",
"max": 10,
"icon": "wine_bottle"
}
},
"strength": [9, 10, 10.5, 11, 11.5, 12, 13, 14, 15, 16, 17]
},
"spirits": {
"name": "Spirits or shots",
"sizes": {
"25": {
"name": "Single",
"size": 0.025,
"id": "single",
"max": 10,
"icon": "spirit_single"
},
"35": {
"name": "Large single",
"size": 0.035,
"id": "lgSingle",
"max": 10,
"icon": "spirit_large_single"
},
"50": {
"name": "Double",
"size": 0.05,
"id": "double",
"max": 10,
"icon": "spirit_double"
},
"70": {
"name": "Large double",
"size": 0.07,
"id": "lgDouble",
"max": 10,
"icon": "spirit_large_double"
},
"700": {
"name": "Bottle",
"size": 0.7,
"id": "bottle700",
"max": 3,
"icon": "spirit_bottles"
},
"1000": {
"name": "Bottle",
"size": 1,
"id": "bottle",
"max": 3,
"icon": "spirit_bottles"
}
},
"strength": [37, 40]
},
"alcopop": {
"name": "Alcopop",
"sizes": {
"275": {
"name": "Small bottle",
"size": 0.275,
"id": "small",
"max": 10,
"icon": "alcopops_small_bottle"
},
"330": {
"name": "Standard bottle",
"size": 0.33,
"id": "std",
"max": 10,
"icon": "alcopops_standard_bottle"
},
"750": {
"name": "Large bottle",
"size": 0.75,
"id": "large",
"max": 10,
"icon": "alcopops_large_bottle"
}
},
"strength": [5, 5.5]
}
}
.map does not work on objects like that,
map() is only for Arrays
Instead you can store the keys in array and use them, like,
import jsonData from '../../config/calculator';
...
//in constructor or any function
let sizes;
sizes={};
for(let i of Object.keys(jsonData)){
if(!sizes[i][0])sizes[i] = [];
for(let j of Object.keys(i.sizes)){
sizes[i].push(jsonData[i].sizes[j])
}
}
this.setState({
sizesArray:sizes
})
Now you can use this.state.sizesArray.map to iterate over sizes, like,
{this.state.sizes[drinkType].map((option, i) =>
<div value={option.id} key={i}>
{option}
</div>
)}
First, import your json inside the component:
import jsonData from '../../config/calculator'; //specify the appropriate location of the json file
Then you can access the "data" in your component in various ways. One way could be:
constructor() {
this.state = {
data: []
}
}
componentDidMount(){
this.setState({data: jsonData});
}
And accordingly, you can use this data(this.state.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()
My goal is to use a tree object to store invoices. The issue I'm running into is that it always puts a "Invoice" model wrapper around each subsequent child. I tried just getting the results and using the Set class to clean up the redundant "Invoice", "children" but I couldn't figure out how to get it to work. I'm using this in an API so basically what I want to be able to do is move up and down the array without having to constantly do invoice.children.invoice.children
In my controller I have:
$results = $this->Invoice->find('threaded', array(
'order' => array('lft ASC') // or array('id ASC')
));
$this->set(array(
'results' => $results,
'_serialize' => 'results'
));
What I'm getting is:
{
"success": true,
"data": [
{
"id": 1,
"parent_id": null,
"lft": 1,
"rght": 30,
"name": "Invoices",
"children": [
{
"Invoice": {
"id": 2,
"parent_id": 1,
"lft": 2,
"rght": 15,
"text": "invoice 001"
},
"children": [
{
"Invoice": {
"id": 3,
"parent_id": 2,
"lft": 3,
"rght": 8,
"text": "invoice_item"
},
"children": [
{
"Invoice": {
"id": 4,
"parent_id": 3,
"lft": 4,
"rght": 5,
"text": "invoice_sub_item"
},
"children": []
},
{
"Invoice": {
"id": 5,
"parent_id": 3,
"lft": 6,
"rght": 7,
"text": "subitem#2"
},
"children": []
}
]
}
]
}
]
}
]
}
Ideally I'd like to have
invoices.invoice.text = "invoice 001"
and
invoices.invoice.invoice_item[0].text = "invoice_item"
Obviously I'll need to add/take away from the array and resubmit with changes. Is this possible or am I just making things harder on myself?