JSON images url instead of base64 - javascript

I'm using Three.js to save and load objects in a database. I'm inserting my objects as JSON.
The problem is that JSON.stringify or toJSON() transform the image url (textures) in base64, and I wanted to keep the http url.
This is the originial JSON:
{
"metadata": {
[...]
},
"geometries": [
{
[...]
}],
"materials": [
{
[...]
}],
"textures": [
{
[...]
}],
"images": [
{
"uuid": "4ED9CE3E-7C8A-4EB7-8CF8-D90B3527DF5F",
"url": "data:image/png;base64,iVBORw0KGgoATyuRZGZVREd0FAERRRBAEBEFwAYEyKqP/Rfozx+5fDYjvpeT/akv+n/J+/7eMjX9Ke8uojP4JVAYAyuj/Ld3Por7fPQ9i8d7vvr8LKNzLg/dn1u1hvQf3q/v92vRX0X/ [...]"
}],
"object": {
[...]
}
}
And the desired kind of JSON would be this :
{
"metadata": {
[...]
},
"geometries": [
{
[...]
}],
"materials": [
{
[...]
}],
"textures": [
{
[...]
}],
"images": [
{
"uuid": "4ED9CE3E-7C8A-4EB7-8CF8-D90B3527DF5F",
"url": "http://www.domain.com/picture/path.png"
}],
"object": {
[...]
}
}
Is there a solution to do this ?

After studying the JSON file and getting my texture path, I did the following:
var objectParsed = SELECTED.toJSON(); //transform the selected object in JSON
textureBase64 = objectParsed.images[0].url; //get the value of the base64 encoded image
objectParsed.images[0].url = texMap; // replace the base64 encoded image with the http texture path
objectParsed = JSON.stringify( objectParsed, null, '\t' );
objectParsed = objectParsed.replace( /[\n\t]+([\d\.e\-\[\]]+)/g, '$1' ); // make the JSON readable
And now it did the trick ! :)

Related

How to create a json object from another json object using JavaScript?

I am really junior with JavaScript and json, so I have this JSON input, and I need to get all that information in the "properties" object to create a new JSON object with just that information.
I'm using a base code like this one, but this is just returning {}.
exports.step = function(input, fileInput) {
var alert = {
'Properties': input.alert.properties
}
return JSON.stringify(alert, undefined, 1);
};
Original JSON:
"value": {
"id": "12345",
"entity": {
"_integrationDefinitionId": "7a6764",
"_integrationName": "Apple Main",
"_beginOn": "2021-09-01T02:20:06.189Z",
"displayName": "apple-onev",
"_accountIdPartitioned": "12345|12",
"_class": [
"Deployment",
"Group"
],
"_version": 3,
"_integrationClass": [
"CiSSP",
"Infrastructure"
],
"_accountId": "123456",
"_id": "1e234567",
"_key": "arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456",
"_type": [
"aws_autoscaling_group"
],
"_deleted": false,
"_rawDataHashes": "1233456==",
"_integrationInstanceId": "54321",
"_integrationType": "aws",
"_source": "integration",
"_createdOn": "2021-07-19T23:19:19.758Z"
},
"properties": {
"webLink": "https://google.com",
"arn": "name",
"region": "us-west-2",
"name": "JonnyAndTheVibes",
"launchConfigurationName": "OtherName",
"minSize": 1,
"maxSize": 4,
"desiredCapacity": 1,
"defaultCooldown": 360,
"availabilityZones": "us-west-2a",
"LoadBalancerNames": "MoreInfo",
"healthCheckType": "EC2",
"healthCheckGracePeriod": 0,
"instanceIds": "InstanceName",
"subnetIds": "subnet",
"terminationPolicies": "Default",
"newInstancesProtectedFromScaleIn": false,
"serviceLinkedRoleARN": "aMoreInfo",
"tag.Name": "atag",
"tag.application": "othertag",
"tag.aws:cloudformation:logical-id": "moretagsp",
"tag.aws:cloudformation:stack-id": "taggigante",
"tag.aws:cloudformation:stack-name": "ydaleconlostags",
"tag.elasticbeanstalk:environment-id": "seguimosmetiendoletags",
"tag.elasticbeanstalk:environment-name": "tag",
"tag.env": "tag",
"tag.team": "tag",
"accountId": "tag",
"tag.AccountName": "tag",
"tag.Production": true,
"#tag.Production": "​"
}
}
I'm sure that it will be a simple solution.
You appear to be trying to grab properties from the wrong object. It should be value not alert.
const json = '{"value":{"id":"12345","entity":{"_integrationDefinitionId":"7a6764","_integrationName":"Apple Main","_beginOn":"2021-09-01T02:20:06.189Z","displayName":"apple-onev","_accountIdPartitioned":"12345|12","_class":["Deployment","Group"],"_version":3,"_integrationClass":["CiSSP","Infrastructure"],"_accountId":"123456","_id":"1e234567","_key":"arn:aws:autoscaling:us-west-2:83712398:autoScalingGroup:asd1238-20c8-41aa-bcec-12340912341:autoScalingGroupName/awseb-e-juancito-stack-AWSEBAutoScalingGroup-123456","_type":["aws_autoscaling_group"],"_deleted":false,"_rawDataHashes":"1233456==","_integrationInstanceId":"54321","_integrationType":"aws","_source":"integration","_createdOn":"2021-07-19T23:19:19.758Z"},"properties":{"webLink":"https://google.com","arn":"name","region":"us-west-2","name":"JonnyAndTheVibes","launchConfigurationName":"OtherName","minSize":1,"maxSize":4,"desiredCapacity":1,"defaultCooldown":360,"availabilityZones":"us-west-2a","LoadBalancerNames":"MoreInfo","healthCheckType":"EC2","healthCheckGracePeriod":0,"instanceIds":"InstanceName","subnetIds":"subnet","terminationPolicies":"Default","newInstancesProtectedFromScaleIn":false,"serviceLinkedRoleARN":"aMoreInfo","tag.Name":"atag","tag.application":"othertag","tag.aws:cloudformation:logical-id":"moretagsp","tag.aws:cloudformation:stack-id":"taggigante","tag.aws:cloudformation:stack-name":"ydaleconlostags","tag.elasticbeanstalk:environment-id":"seguimosmetiendoletags","tag.elasticbeanstalk:environment-name":"tag","tag.env":"tag","tag.team":"tag","accountId":"tag","tag.AccountName":"tag","tag.Production":true,"#tag.Production":"​"}}}';
function getAlert(dsta) {
// Destructure the properties object from the
// data's value property
const { properties } = data.value;
// Create a new object with it
const alert = { properties };
// Return the string
return JSON.stringify(alert, null, 2);
};
// Parse the JSON
const data = JSON.parse(json);
// Call the function with the parsed data
const alert = getAlert(data);
console.log(alert);
Additional information
Destructuring assignment
use this function :
function assignJsons(...jsons) {
const convertToObject = jsons.map(json => {
return JSON.parse(json)
});
return JSON.stringify(Object.assign(...convertToObject))
}
//test
console.log(assignJsons(`{"name" : "alex", "family" : "mask"}`, `{"family" : "rejest"}`))
if you want a completely new object
var newJsonObject = JSON.parse('{ "properties":'
+ JSON.stringify (origJson.value.properties) + "}");
or
var newJsonObject={"properties":Object.assign ({}, origJson.value.properties)};

Manipulating json before sending to a database

I'm pulling in some data from Airtable API using node and airtable.js. Im using linked fields in the airtable database. The data look like this :
{
"id": "recct1MELnXEJGj6Z",
"fields": {
"Household": "Betts",
"Guests": [
"recWONC10o06E4IN0",
"recLwxndGevZ7HeUG"
],
"Name (from Guests)": [
"Margaret",
"Terry"
]
},
"createdTime": "2021-09-11T15:48:51.000Z"
}
I would like to reformat before I push to MongoDB database so that it looks like this:
{
"id": "recct1MELnXEJGj6Z",
"Household": "Betts",
"Guests": [
{
"_id" : "recWONC10o06E4IN0",
"name" : "Margaret"
},
{"_id" : "recLwxndGevZ7HeUG",
"name" : "Terry"
},
],
"createdTime": "2021-09-11T15:48:51.000Z"
}
Thanks in advance
You basically need to extract keys and values from the fields object, assign them directly to the JSON and then delete the fields object.
const json = {
"id": "recct1MELnXEJGj6Z",
"fields": {
"Household": "Betts",
"Guests": [
"recWONC10o06E4IN0",
"recLwxndGevZ7HeUG"
],
"Name (from Guests)": [
"Margaret",
"Terry"
]
},
"createdTime": "2021-09-11T15:48:51.000Z"
}
Object.entries(json.fields).forEach(([key, value]) => (json[key] = value));
delete json.fields;
console.log(json);
Or you could create a new JSON object like so:
const json = {
"id": "recct1MELnXEJGj6Z",
"fields": {
"Household": "Betts",
"Guests": [
"recWONC10o06E4IN0",
"recLwxndGevZ7HeUG"
],
"Name (from Guests)": [
"Margaret",
"Terry"
]
},
"createdTime": "2021-09-11T15:48:51.000Z"
}
const newJson = {...json, ...json.fields};
delete newJson.fields;
console.log(newJson);

Use data from Quandl API to show in Appsmith table widget

I am building a web-app and want to connect data from Quandl through its JSON API.
However, the JSON I get from quandl has the column names separate from the data itself, check below:
{
"datatable": {
"data": [
[
"AAPL",
"MRY",
"2020-12-31",
"2020-09-26",
"2020-09-26",
"2021-07-28",
-406000000,
323888000000,
325562500000
]
],
]
],
"columns": [
{
"name": "ticker",
"type": "String"
},
{
"name": "dimension",
"type": "String"
},
{
"name": "calendardate",
"type": "Date"
},
{
"name": "datekey",
"type": "Date"
},
{
"name": "reportperiod",
"type": "Date"
},
{
"name": "lastupdated",
"type": "Date"
},
{
"name": "accoci",
"type": "Integer"
},
{
"name": "assets",
"type": "Integer"
},
{
"name": "assetsavg",
"type": "Integer"
}
]
},
"meta": {
"next_cursor_id": null
}
}
When I use this data in Appsmith, it can not infer the column names. Is there a simple javascript code to combine the column names with the data? Thank you!
This is possible with a simple JS snippet, Now my code written is not that great but will work in this case (Can be optimised)
{{
function() {
let tableData = [];
_.map(_d.datatable.data, (v, i) => {
let set = {}
_.map(v, (x, k) => {
var obj = {[_d.datatable.columns[k].name]: x}
set = {...set, ...obj}
})
tableData.push(set)
})
}()
}}
In the above snippet _d is the data which you receive, We map the array value index with the given column index and create a new object out of it, Also since this is a multiline JS code, In Appsmith we need to write this inside an IIFE like above.

I need remove unnecessary json objects form my result json file using javascript

I have result json file with 10000 of lines. inside the one array object there are some unnecessary json object i need remove. I have tried so many ways but it's didn't work for me. herewith the piece line of json file
[
{
"product_id": "easybridge",
"errors": []
},
{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "productization",
"errors": []
},
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
],
"properties": {
"trend": {
"$id": "#/properties/test_ids/items/properties/trend",
"examples": [
true
]
},
"display": {
"$id": "#/properties/test_ids/items/properties/display",
"type": "boolean",
"examples": [
true
]
},
"test_id": {
"$id": "#/properties/test_ids/items/properties/test_id",
"type": "string",
},
"test_name": {
"$id": "#/properties/test_ids/items/properties/test_name",
"type": "string",
},
"maintenance": {
"$id": "#/properties/test_ids/items/properties/maintenance",
"type": "boolean",
]
},
"instance": {
"trend": false,
"display": false,
"test_id": "8597ae3c-e2a9-45c7-b279-bde1710681be",
"test_name": "Equella Pearsonresearch Ping Test",
"nrAlertStatus": "enabled",
"test_locations": [
{
"alert_state": false,
"location_name": "AWS_US_WEST_2",
"location_label": "Portland, OR, USA",
"included_to_health": false
}
],
"included_to_health": false,
"critical_alert_threshold": 60
},
"name": "required",
"argument": "maintenance",
"stack": "instance.test_ids[1] requires property \"maintenance\""
{
"product_id": "easybridge",
"errors": []
},
I just need only
{
"product_id": "equella",
"errors": [
{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
}
},
if the errors json array is not empty. i don't need even this json how can i remove "schema" json object and other unnecessary json object and arrays specially "schema" json object using java script or java. please help
Loop through the array, look at each object, and create a new array by copying over the data you need.
For instance, I'm taking it you don't care about an object if its array of errors is empty, and that you don't care about the schema ever:
let newJSON = [];
//Assume the json variable is the parsed JSON file you posted.
for (let element of json) {
//Must have at least one error
if (element.errors.length > 0) {
//Create a new object
let newObj = {
"product_id" : element.product_id,
"errors" : []
};
//Add each errror
for (let error of element.errors) {
//Only copy across what we need
newObj.errors.push({
"property" : error.property,
"message" : error.message
});
}
//Add object to our new array of JSON
newJSON.push(newObj);
}
}
//newJSON is your processed JSON output
The easiest solution can be:
const records = [{
"product_id": "learningstudio",
"errors": []
},
{
"product_id": "pearsontestprep",
"errors": []
},
{
"product_id": "equella",
"errors": [{
"property": "instance.test_ids[1]",
"message": "requires property \"maintenance\"",
"schema": {
"$id": "#/properties/test_ids/items",
}
}]
}];
const filteredRecords = records.map((record) => {
record.errors = record.errors.map((error) => {
return {property: error. property, message: error.message};
});
return record;
});
console.log(filteredRecords);
You can use map and destructuring assignment to capture only desired properties
let json = [{"product_id": "equella", "errors": [{"property": "instance.test_ids[1]","message": "requires property \"maintenance\"",'xyz': 'not needed','useless': 'not needed',},{'xyz': 'not needed',}]},]
let op = json.map(({product_id,errors}) =>{
let { property, message } = errors[0]
return { product_id, errors: {property,message}}
})
console.log(op)

Create a nested JSON Object with Javascript

I´d like to create a JSON-Object for a Google API-Request. Only content is needed to change. My solution gives me an invalid JSON-Format and is more a hack. Is there an easier way to do this? Thank your for your hints.
The necessary format look like this:
{
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
JS
var cvs = cvs.substring('data:image/png;base64,'.length);
var json1 = '{"requests":[{ "image":{ "content":"'
var json2 = '"}, "features": [{"type":"DOCUMENT_TEXT_DETECTION"}] } ]}'
var entireJson = json1 + cvs + json2;
var ocrImage = JSON.stringify(entireJson);
What you have done in your example is initializing a Javascript Object.
JSON.parse(object_string); is not necessary. You may initialize it directly:
var ocrImage = {
"requests": [
{
"image": {
"content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
]
}
console.log(ocrImage)

Categories

Resources