I would like to transform an object got from a NoSQL Database using a DTO, so, I inspect the object in a for..in loop to get only what I want to keep:
for (const attribute in result) {
if (result.hasOwnProperty(attribute)) {
console.log(`${attribute} belongs to object!`);
}
}
I wonder why :
I have to use hasOwnProperty method as I loop over the object to get attributes
my object have a 'nutriments' attribute, but... never consoled
Here's a portion of the original object :
...
nutriments:
{ sugars: 6.5,
'nova-group_serving': 4,
fiber_value: 2.5,
'nutrition-score-uk_100g': 1,
energy_value: 1160,
salt_100g: 1.08,
'nutrition-score-uk': 1,
fiber_100g: 2.5,
proteins: 8.5,
'nova-group_100g': 4,
carbohydrates_unit: 'g',
'saturated-fat_100g': 0.4,
'nutrition-score-fr_100g': 1,
salt_unit: 'g',
'saturated-fat_unit': 'g',
sugars_100g: 6.5,
sugars_value: 6.5,
'saturated-fat_value': 0.4,
carbohydrates_value: 49.2,
fat_unit: 'g',
fiber: 2.5,
proteins_value: 8.5,
fat_value: 4.3,
sugars_serving: 5.13,
sodium_value: 0.43200000000000005,
fiber_serving: 1.98,
sodium_unit: 'g',
energy_serving: 916,
sodium_serving: 0.34099999999999997,
proteins_unit: 'g',
carbohydrates: 49.2,
energy: 1160,
salt_value: 1.08,
sodium_100g: 0.43200000000000005,
'nova-group': 4,
'saturated-fat_serving': 0.316,
proteins_serving: 6.72,
'nutrition-score-fr': 1,
energy_100g: 1160,
energy_unit: 'kJ',
fiber_unit: 'g',
'carbon-footprint-from-known-ingredients_product': 416,
sugars_unit: 'g',
proteins_100g: 8.5,
'carbon-footprint-from-known-ingredients_100g': 75.6,
carbohydrates_serving: 38.9,
salt_serving: 0.8530000000000001,
fat_serving: 3.4,
salt: 1.08,
carbohydrates_100g: 49.2,
'saturated-fat': 0.4,
fat_100g: 4.3,
fat: 4.3,
'carbon-footprint-from-known-ingredients_serving': 59.7,
sodium: 0.43200000000000005 },
...
I edit my for in loop to trace "attributes" and the attribute "nutriments" was listed, but... result['nutriments'] is undefined and result.hasOwnProperty('nutriments') returns false...
for (const attribute in result) {
console.log(`Discovering ${attribute} belongs to object!`);
if (result.hasOwnProperty(attribute)) {
console.log(`${attribute} belongs to object!`);
}
}
This behaviour is observable for some other object attributes, but I can get the attribute value with a result.attributeName.
So, what can explain this behaviour ?
hasOwnProperty returns false for attributes that are inherited. My guess would be that the nutriments property is in fact inherited by this object. We use it to actually avoid some of the inherited properties.
Another possibility is that the object is either a Proxy or has some of its properties protected with .defineProperty, making them either not iterable or not "get-able".
More info would be needed for proper diagnosis / solution.
Sorry for this question... I found the solution exploring my own mongoose Schema, even if MongoDB returns the whole content of the document, this one is handled by the defined Schema, and... i forgot to add the "nutriments" property.
Related
I have a pre-defined API, like:
{
time : some_time,
height : {1: 154, 2: 300, 3: 24},
color : {1: 'red', 2: 'blue', 3: 'green'},
age : {1: 27, 2: 324, 3: 1},
... many, many more keys.
}
I have no control of this API, so cannot change its structure.
Each integer key inside the sub dictionaries are linked and part of one record. For example the object that is 154 in height, is also colour: red and age: 27.
I am aware one strategy to work with this is to have separate serialisers for each field.
class MySerializer(serializers.ModelSerializer):
# Nested serializers
height = HeightSerializer()
colour = ColourSerializer()
age = AgeSerializer()
etc, etc, etc
But that still gives me messy data to work with, that requires lots of update() logic in the serializer.
What I instead want to do is have one nested serializer that has access to the full request data, and can work with height, colour and age simultaneously and return me something like from the to_internal_value() method:
{
['record' : 1, 'height': 154, 'colour' : 'red', 'age' : 27],
['record' : 2, 'height': 300, 'colour' : 'blue', 'age' : 324],
['record' : 3, 'height': 24, 'colour' : 'green', 'age' : 2],
}
But unfortunately the height serializer only seems to have access to information on fields called height. I am aware I can user source="foo" in the init call, but then it only has access to a field called "foo". I want it to have access to all fields.
I noticed there is a source='*' option, but it doesn't work. My init method of the serializer never gets called unless there is a key "height" in the api call.
Any ideas how I can have a nested serialiser that has access to all the data in the request?
Thanks
Joey
So I'm currently using JSON.NET in Visual Studio to parse my JSON since using deserialization is too slow for what I'm trying to do. I'm pulling stock information from TD Ameritrade and can request multiple stocks at the same time. The JSON result below is from pulling only 1. As you can see, the first line is "TQQQ". If I were to pull more than one stock, I'd have "TQQQ", then "CEI" in separate blocks representing different objects.
Under normal deserialization, I could just say to deserialize a dictionary and it would put them into the dictionary accordingly with whatever class I had written for it to populate. However, since I need to parse line by line, is there a clean way of being able to tell when I've arrived to the next object?
I could say to keep track of the very last field and then add the next line (the next ticker's name) to dictionary, but that seems a little hacky.
I don't think any VB code is necessary besides the initial startup of creating a new JSONReader.
{
"TQQQ": {
"assetType": "ETF",
"symbol": "TQQQ",
"description": "ProShares UltraPro QQQ",
"bidPrice": 54.59,
"bidSize": 200,
"bidId": "Q",
"askPrice": 54.6,
"askSize": 8000,
"askId": "Q",
"lastPrice": 54.6,
"lastSize": 100,
"lastId": "P",
"openPrice": 51.09,
"highPrice": 54.6,
"lowPrice": 50.43,
"bidTick": " ",
"closePrice": 48.92,
"netChange": 5.68,
"totalVolume": 14996599,
"quoteTimeInLong": 1540493136946,
"tradeTimeInLong": 1540493136946,
"mark": 54.6,
"exchange": "q",
"exchangeName": "NASDAQ",
"marginable": true,
"shortable": true,
"volatility": 0.02960943,
"digits": 4,
"52WkHigh": 73.355,
"52WkLow": 38.6568,
"nAV": 0,
"peRatio": 0,
"divAmount": 0,
"divYield": 0,
"divDate": "2016-12-21 00:00:00.0",
"securityStatus": "Normal",
"regularMarketLastPrice": 54.6,
"regularMarketLastSize": 1,
"regularMarketNetChange": 5.68,
"regularMarketTradeTimeInLong": 1540493136946,
"delayed": true
}
}
Is there a clean way of being able to tell when I've arrived at the next object?
Yes, assuming you are using a JsonTextReader you can look at the TokenType property and check whether it is StartObject. This corresponds to the opening braces { in the JSON. There is also an EndObject token type corresponding to the closing braces }, which will probably also be useful depending on how your code is written.
Typical usage pattern is something like this:
If reader.TokenType == TokenType.StartObject Then
While reader.Read() AndAlso reader.TokenType <> JsonToken.EndObject
' process properties of the JSON object
End While
End If
I am having a JSON array of numbers like [16, 9, 11, 22, 23, 12]. I would like to get the index of numbers within the array. For example is I say that I would like to have the index of 9, it should return 1.
I tried using below mentioned query in MySQL, but getting null.
SELECT JSON_SEARCH(CAST('[16, 9, 11, 22, 23, 12]' AS JSON),'one',9)
Do you guys have solution for this ?
CAST is not necessary here. But array values should be quoted as
JSON_SEARCH(json_doc, one_or_all, search_str[, escape_char[, path] ...])
Returns the path to the given string within a JSON document.
SELECT json_search('["16", "9", "11", "22", "23", "12"]', 'one', '9');
returns "$[1]"
I have a problem writing a query to extract a table out of the arrays from a json file: The problem is how to get the information of the array “clientPerformance” and then make them all in a normal sql table.
The file looks like this:
"clientPerformance":[
{
"name":"opportunity",
"clientProcess":{
"value":3620000.0,
"count":1.0,
"min":3620000.0,
"max":3620000.0,
"stdDev":0.0,
"sampledValue":3620000.0
},
"networkConnection":{
"value":10000.0,
"count":1.0,
"min":10000.0,
"max":10000.0,
"stdDev":0.0,
"sampledValue":10000.0
},
"receiveRequest":{
"value":9470000.0,
"count":1.0,
"min":9470000.0,
"max":9470000.0,
"stdDev":0.0,
"sampledValue":9470000.0
},
"sendRequest":{
"value":1400000.0,
"count":1.0,
"min":1400000.0,
"max":1400000.0,
"stdDev":0.0,
"sampledValue":1400000.0
},
"total":{
"value":14500000.0,
"count":1.0,
"min":14500000.0,
"max":14500000.0,
"stdDev":0.0,
"sampledValue":14500000.0
},
"url":"https://xxxx",
"urlData":{
"base":"/main.aspx",
"host":"xxxx",
"hashTag":"",
"protocol":"https"
}
}
]
I tried to use Get array elements method and other ways but I am never able to access to clientProcess, networkConnection.. elements
I tried to use for exampls this one:
Select
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 0), 'name') AS Name,
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 1), 'clientProcess.count') AS clientProcessCount,
FROM [app-insights-blob-dev] Input
I would appreciate any help :)
I slightly edited your query to return the clientProcessCount.
(I changed the array index from 1 to 0). Also make sure your JSON object starts with { and ends with }.
Select
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 0), 'name') AS Name,
GetRecordPropertyValue(GetArrayElement(Input.clientPerformance, 0), 'clientProcess.count') AS clientProcessCount
FROM [app-insights-blob-dev] Input
For other examples to query complex objects with ASA, don't hesitate to look at this blog post.
How do I insert an element at arbitrary position of Immutable.js List?
You are looking for the splicemethod:
Splice returns a new indexed Iterable by replacing a region of this Iterable with new values.
splice(index: number, removeNum: number, ...values: any[])
Where you can specify the index and if you write 0 as removeNum it will just insert the values at the given position:
var list = Immutable.List([1,2,3,4]);
console.log(list.toJS()); //[1, 2, 3, 4]
var inserted = list.splice(2,0,100);
console.log(list.toJS()); //[1, 2, 3, 4]
console.log(inserted.toJS()); //[1, 2, 100, 3, 4]
Demo JSFiddle.
It is worth pointing out that you can also use the insert method which is in fact synonymous with list.splice(index, 0, value) but it feels more intuitive and improves readability greatly.
const myImmutableList = Immutable.fromJS(['foo', 'baz'])
const newList = myImmutableList.insert(1, 'bar')
console.log(newList.toJS()) //["foo", "bar", "baz"]