I am new to javascript and to JSON, so please forgive me.
If I have the following JSON Object, how would I console.log() out the value of autonum?
{
"database": "testdb",
"table": "path",
"affectedColumns": [
{
"name": "autonum",
"charset": null,
"type": 8
},
{
"name": "TimeStamp",
"charset": null,
"type": 18,
"metadata": {
"decimals": 0
}
},
{
"name": "FilePath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirPath",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "DirName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "EventName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileName",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 256
}
},
{
"name": "FileExt",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 10
}
},
{
"name": "FileSize",
"charset": null,
"type": 3
},
{
"name": "MainFlag",
"charset": null,
"type": 1
},
{
"name": "DeleteFlag",
"charset": null,
"type": 1
},
{
"name": "Status",
"charset": "latin1",
"type": 15,
"metadata": {
"max_length": 255
}
},
{
"name": "ProcessedFlag",
"charset": null,
"type": 1
}
],
"changedColumns": [],
"fields": {
"autonum": 121,
"TimeStamp": "2016-01-13T00:21:13.000Z",
"FilePath": "c:/1E0304F120151223030158001.mp4",
"DirPath": "c:\\",
"DirName": null,
"EventName": null,
"FileName": "1E0304F120151223030158001.mp4",
"FileExt": ".mp4",
"FileSize": 2218108,
"MainFlag": 0,
"DeleteFlag": 0,
"Status": null,
"ProcessedFlag": 0
}
}
Depending on which autonum you want, and assuming your variable storing the JSON is data, you'll want to do something as follows:
console.log(data.fields.autonum);
or
console.log(data.affectedColumns[0].name);
You'd use the following code, assuming the json object is called record:
console.log(record.fields.autonum);
You have two main ways of doing it. Both are correct ways. Lets say your object is named obj. Use console.log as following:
console.log(obj.fields.autonum)
console.log(obj['fields']['autonum'])
First case is easier as compare to second case.
Second case is safer as it will allow you to even take care of keys which have spaces e.g.
var my_other_object = {
'Santa Clara': 'USA',
'Toronto': 'Canada'
};
console.log(my_other_object['Santa Clara']) // Output will be 'USA'
For your understanding, in above object 'Santa Clara' and 'Toronto' are called 'keys' of my_other_object and 'USA', 'Canada' are called 'values' of those 'keys'.
So JSON object is essentially combination of key:value pairs.
P.S. Never apologize while asking a question all questions are valid but it is good to always search before asking. Still, people are always happy to help here. We all have went through same phases. :)
Lets say your object name var data, then data.fields.autonum would give us value 121
console.log(data.fields.autonum)
Just FYI:
As it is stated on MDN website:
some JavaScript is not JSON, and some JSON is not JavaScript
Just in order to improve understanding of vocabulary, 'JSON Object' is not a thing in our context ... it is
a syntax for serializing objects
Related
i have json file in an api source, The json output is as below.
{
"data": {
"metadata": { },
"segments": [
{
"type": "overview",
"attributes": {},
"expiryDate": "2021-07-03T00:25:07.8647619+00:00",
"stats": {
"timePlayed": {
"rank": null,
"percentile": 93,
"displayName": "Time Played",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 6635877,
"displayValue": "1,843h 17m",
"displayType": "TimeSeconds"
},
"score": {
"rank": null,
"percentile": 85,
"displayName": "Score",
"displayCategory": "General",
"category": "general",
"metadata": {},
"value": 210790,
"displayValue": "210,790",
"displayType": "Number"
}
}
}
],
"availableSegments": [],
"expiryDate": "2021-07-03T00:25:07.8647619+00:00"
}
}
I want to get the data > segments > stats values in this json output using fetch method. My Codes;
fetch(csgo2, {"headers": {"TRN-Api-Key": "xxxxxxxxxxxxxxxxxxxxxxxxx"}}).then(res => res.json()).then(body => {
const { timePlayed, score} = body.data.segments[0];
console.log(timePlayed.value)//undefined always output console.
})
I'm trying to get the data > segments > score or timesplayed value as in the code block, but I keep getting the undefined error from the console.
what i want to do is get the score or timesplayed value
The issue is you should use body.data.segments[0].stats. The body is an object with a data property, not the data property itself.
For reference I have zero javascript knowledge or any coding knowledge. I typically just hook up applications via IPASS applications that don't require any coding knowledge. However, I found out I need to inject some javascript into the application in order to avoid an error message.
I have the below JSON record.
I need to get rid of the empty array (sorry... if it is not an array but an object? Like I said, no javascript knowledge).
In the below code essentially what I want is to completely delete this line, because there is nothing inside the brackets and it is causing errors:
"lineitemsdata": []
Full JSON record below for reference
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [
{
"id": "5230410841",
"type": "company_to_deal"
}
]
}
},
"dealdata": [
{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [
{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}
],
"DealOwner": [
{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}
],
"NetSuiteCustomerID": 1745
}
Item inside object is called a property. If you (for some reason) have to include the property, but don't want it to have any value you can either set it's value to null or undefined.
I suspect I'm going to get criticized for this, but here is a quick and dirty way of removing this specific problem through string replacement. The 'right' way would be to break down your json into separte objects until you get to the level where the offending object lives, remove it, then rebuild it all back. For what it's worth, here's an alternative to that
let json = {
"id": "5399286500",
"properties": {
"state": "AB",
"website": null,
"zip": "T3B5Y9"
},
"createdAt": "2021-02-18T22:13:06.111Z",
"updatedAt": "2021-05-17T14:35:09.540Z",
"archived": false,
"associations": {
"deals": {
"results": [{
"id": "5230410841",
"type": "company_to_deal"
}]
}
},
"dealdata": [{
"id": "5230410841",
"properties": {
"hs_lastmodifieddate": "2021-05-13T14:00:33.101Z",
"hs_object_id": "5230410841",
"hubspot_owner_id": "52200226"
},
"associations": {
"line items": {
"results": [{
"id": "1468189759",
"type": "deal_to_line_item"
},
{
"id": "1468189760",
"type": "deal_to_line_item",
"lineitemsdata": []
}
]
}
}
}],
"DealOwner": [{
"id": "52200226",
"email": "email#email.com",
"firstName": "Bob"
}],
"NetSuiteCustomerID": 1745
}
json = JSON.stringify(json)
let strstart = json.indexOf('"lineitemsdata":[]');
let commapos = json.lastIndexOf(',', strstart);
json = json.substr(0, commapos) + " " + json.substr(commapos + 1);
json = json.replace('"lineitemsdata":[]', '');
json = JSON.parse(json)
console.log(json)
You can use this to strip any empty lineitems arrays from your json.
Assuming the reference to your record is json
for(dealIdx in json.dealdata) {
for (resultIdx in json.dealdata[dealIdx].associations["line items"].results) {
let lineItemsData = json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
if (lineItemsData != undefined && lineItemsData.length === 0 ) {
delete json.dealdata[dealIdx].associations["line items"].results[resultIdx].lineitemsdata
}
}
}
following up on my previous question about transforming data using lodash, this time i require output to be an object properties instead of being a collection. I appreciate the help and if someone can also guide me where to begin properly so i have a better understanding of these concepts
Sample Data
{
"changeAccount": {
"add": [
{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
}
],
"remove": [
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
}
]
},
"changeproduct": {
"add": [
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
],
"remove": []
}
}
Expected Result
var sample = [{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
},
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
},
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
]
Here is one way to do it:
chain(data)
.values()
.map(_.values)
.flatMapDeep()
.value()
So what's happening here is:
Start with our data which is an object
Use .values to return only the values of our top level properties (i.e. strip away changeProduct and changeAccount
Map the resulting items in the array to only the values of our objects (i.e. strip away add and remove) using .values again
Flatten the entire array recursively so we end up with an array that is one level deep using .flatMapDeep
You might also notice the chain(data) syntax, this is just a way to improve the readability and sometimes performance of your lodash code, so that you don't have to nest each lodash function that you use. Check out the docs on chain for more info.
I have a (long) json schema and I already validate the json objects in my code based on that schema.
My problem/use-case is to translate/restructure an incoming json object to a new json object that satisfies my schema.
I realized however, that it isn't that easy to do, especially if you look for an "adaptive" solution.
Adaptive meaning that the code doesn't care about changes of the schema or the incoming object.
So my first approach was to create a class that contains a mapping of the incoming object to a valid object.
This means however that I have to write this map by hand and update it if I change the schema.
So is there a solution where I can insert any schema, any non-valid (based on schema) json object and get a valid object out?
Or at-least a way to generate a valid json object template, where you can insert the data of the incoming invalid json object?
This way I could at least be independent from schema changes.
PS: I tried to solve this problem in an abstract way, but if needed I can provide schema and the invalid object.
PPS: My environment is node.js.
Edit: E.g.:
Schema
{
...//other Schema stuff (using draft-07)
"tokens": {
"$id": "/token",
"title": "Token",
"description": "A representation of a word in a Message with all the nlp Analysis results and infos",
"type": "array",
"minItems": 1,
"items": {
"$ref": "#/definitions/tokens/definitions/token"
},
"token": {
"$id": "#token",
"type": "object",
"required": [
"id",
"text"
],
"properties": {
"id": {
"description": "global (level:conversation) unique identifier to identify a token (cumulative)",
"type": "number",
"exclusiveMinimum": 0,
"uniqueItems": true
},
"isText": {
"description": "Describes if the token is a real semantic word or a whitespace or similar",
"type": "boolean"
},
"text": {
"description": "the actual content of the token",
"type": "string",
"pattern": "^(.+)$"
},
"word_index": {
"description": "Index of a word in a text",
"type": "number",
"exclusiveMinimum": 0,
"uniqueItems": true
},
"punctuation": {
"description": "The punctuation that needs to be rendered before/after that token. TODO: finish it",
"type": "string"
},
"characterOffsetBegin": {
"type": "integer",
"description": "The inclusive character index in the sentence where this token begins"
},
"characterOffsetEnd": {
"type": "integer",
"description": "The exclusive character index in the sentence where this token ends"
},
"lemma": {
"type": "string",
"pattern": "^(.+)$"
},
"pos": {
"type": "string",
"description": "part of speech tag",
"pattern": "^(.+)$"
},
}
},
"text_label": {
//This is where it gets difficult
"description": "Label of the text for the frontend. ",
"type": "object",
"required": [
"name",
"begin",
"end"
],
"additionalProperties": false,
"properties": {
"name": {
"description": "Name of the label",
"type": "string"
},
"begin": {
"description": "Token index where the label starts",
"type": "number"
},
"end": {
"description": "Token indes where the label ends",
"type": "number"
}
}
}
}
}
Object to translate:
{
"text": "Hello, my name is Somebody. ",
"sentences": [
{
"index": 0,
"tokens": [
{
"index": 1,
"word": "Hello",
"originalText": "Hello",
"characterOffsetBegin": 0,
"characterOffsetEnd": 5,
"before": "",
"after": "",
"pos": "UH",
"lemma": "hello"
},
{
"index": 2,
"word": ",",
"originalText": ",",
"characterOffsetBegin": 5,
"characterOffsetEnd": 6,
"before": "",
"after": " ",
"pos": ",",
"lemma": ","
},
{
"index": 3,
"word": "my",
"originalText": "my",
"characterOffsetBegin": 7,
"characterOffsetEnd": 9,
"before": " ",
"after": " ",
"pos": "PRP$",
"lemma": "my"
},
{
"index": 4,
"word": "name",
"originalText": "name",
"characterOffsetBegin": 10,
"characterOffsetEnd": 14,
"before": " ",
"after": " ",
"pos": "NN",
"lemma": "name"
},
{
"index": 5,
"word": "is",
"originalText": "is",
"characterOffsetBegin": 15,
"characterOffsetEnd": 17,
"before": " ",
"after": " ",
"pos": "VBZ",
"lemma": "be"
},
{
"index": 6,
"word": "Somebody",
"originalText": "Somebody",
"characterOffsetBegin": 18,
"characterOffsetEnd": 26,
"before": " ",
"after": "",
"pos": "NN",
"lemma": "somebody"
},
{
"index": 7,
"word": ".",
"originalText": ".",
"characterOffsetBegin": 26,
"characterOffsetEnd": 27,
"before": "",
"after": "",
"pos": ".",
"lemma": "."
}
],
"basicDependencies": []
}
]
}
Note: that this is corenlp analysis result that can change based on the annotator used.
Edit2: adding example of a correct object:
{ ...other parts of the object
tokens:[
{ id:1, text: 'Hello', isText: true, word_index: 0, characterOffsetBegin:0, characterOffsetEnd: 5, lemma: 'hello', pos:'UH', ...},
{...},
{...}
],
text_label:{
name: 'joy', begin: 0, end: 3
}
}
or another text_label:
text_label:{
name: 'PERSON', begin: 4, end: 5
}
Edit: Difference:
As you can see, some changes a suttle like index->word_index, some are additional information like id, but some need a bit more like the text_label.
corenlp. It could also happen that I need to unify 2 objects together. which is the case of the 'anger' text_label but isnt with the PERSON text_label.
So Im looking for some kind of json Object/Schema manager where translations, validations get easy and dont need hard coded mappings or the generation of that mappings is easy.
I am using Breeze.js in my project and the following query returns me all the group entities that I have in local cache although only one of them has group==group
breeze.EntityQuery.from('Groups').using(manager).where('group', '==', 'group').executeLocally();
Here my metadata definition:
{
"shortName": "Group",
"namespace": "CM.Models",
"baseTypeName": "Entity",
"autoGeneratedKeyType": "Identity",
"defaultResourceName": "Groups",
"dataProperties": [
{
"name": "groupID",
"dataType": "String",
"maxLength": 32,
"defaultValue": "",
"validators": [
{
"name": "maxLength",
"maxLength": 32
}
]
},
{
"name": "group",
"dataType": "String",
"maxLength": 32,
"defaultValue": "",
"validators": [
{
"name": "required"
},
{
"name": "maxLength",
"maxLength": 32
}
]
},
{
"name": "groupMembers",
"dataType": "String",
"isScalar": false,
"defaultValue": []
}
]
}
Is it a bug of Breeze.js?
For reference, I found the answer after digging into breeze.js code. It turns out that it is possible to escape the evaluation side. Therefore the query becomes:
breeze.EntityQuery.from('Groups').using(manager).where('group', '==', "'group'").executeLocally();
"'group'" insetad 'group'