I have a json objectlike this
{"test": [{"href": "http://sdfsd.fd"}], "test2": [{"href": "http://sdfsd.fd"}]}
What I want to do is interate over all the links in the json, every likn point to another json object. then i want to get the json from the links, and replace the links with that json, so it comes like something like this:
{"test": {somejson}, "test2": {somejson}}
can this be done? right now I tried with a nested for loop, but the loop doesnøt care that the hhtp request hasn't got a response, before continuing in the loop, resulting in nothing is gonna be edited.
EDIT:
my code so far looks like this:
self.buildJSON = function(json) {
var links = [];
for(var post in json){
// console.log(json[post]['_links']);
for(var link in json[post]['_links']){
links.push(json[post]['_links'][link][0]['href']);
}
}
// var regex = /(http[s]?:\/\/)?([^\/\s]+)(.*)/
// for(link in links){
// var match = regex.exec(links[link]);
// var host = match[1]+match[2];
// var path = match[3];
// links[link] = {"host": host, "path": path};
// }
for(link in links){
request(links[link], function(error, response, body){
if (!error && response.statusCode == 200) {
links[link] = body;
}
})
}
console.log(links);
fs.writeFile(self.jsonfile, JSON.stringify(json));
the Json something like this ('_links' is part of a bigger json):
_links: {
self: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts/19"
}
],
collection: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts"
}
],
about: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/types/post"
}
],
author: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/users/1"
}
],
replies: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/comments?post=19"
}
],
version-history: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/posts/19/revisions"
}
],
wp:featuredmedia: [
{
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/media/130"
}
],
wp:attachment: [
{
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/media?parent=19"
}
],
wp:term: [
{
taxonomy: "category",
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/categories?post=19"
},
{
taxonomy: "post_tag",
embeddable: true,
href: "http://wordpress.sutdigselv.dk/wp-json/wp/v2/tags?post=19"
}
],
curies: [
{
name: "wp",
href: "https://api.w.org/{rel}",
templated: true
}
]
}
You need to parse your JSON first to get the links (maybe put them in an array). (hint: use JSON.stringify() and it becomes a string that you can parse)
Then iterate over each array element and send XHR requests (hint: XMLHttpRequest object). If you want to 'care' for each response, then use xhttp.open(method,url,false) and xhttp.send(). The 'false' will tell that Asynchronous mode is off and so it becomes synchronous. Beware of performance issues now since its synchronous. Read more here
Now create your own JSON object by storing the links in a string and using json.parse(string) to convert it to json
Related
I have a object like this.
sliderArray:
[
"../assets/slides/1.jpg",
"../assets/slides/2.jpg",
]
Can I reformat it like this in Vue?
sliderArray2:
[
{url: require("../assets/slides/1.jpg")},
{url: require("../assets/slides/2.jpg")},
]
This is easy to do with a map, which applies the same function to every element of an array
let obj = { sliderArray: [
"../assets/slides/1.jpg",
"../assets/slides/2.jpg",
]
};
function formatArray(a) {
return a.map(x => { return { url: require(x) } });
}
obj.sliderArray = formatArray(obj.sliderArray);
I want to retrieve all the key values from a JSON file. For example in :
{
"total_count": 6,
"incomplete_results": false,
"items": [
{
"url": "https://api.github.com/repos/Samhot/GenIHM/issues/6",
"id": 293237635,
"number": 6,
"title": "Rechercher des documents",
"user": {
"login": "Samhot",
"id": 7148311
]
}
I would like to get :
["total_count", "incomplete_results", "items", "url", "url", "number", "title", "user", "login", "id"]
I have a function which return the content of my JSON in an observable :
getConfig(): Observable<any> {
return this.http.get<any>(this.myURL);
}
After that the data are reformated with .map to get only the keys with the Object.keys() function :
merge()
.pipe(
startWith({}),
switchMap(() => {
return this.getConfig();
}),
map(data => {
return Object.keys(data.items[0]);
}
)
)
.subscribe(data => {
this.dispo = data;
});
My problem is that i get only the keys that are in the level of the JSON I told
(data.items[0]) and not the ascendants or the descendants.
Of course I can create multiple requests but it asks to know in advance the structure of the JSON, what I want is to make it generic ...
How can I do to have an array with with all of my keys regardless of the structure of the JSON ?
Thanks in advance !
You would need to do a recursive function like:
function getDeepKeys(obj) {
const keys = Object.keys(obj);
const childKeys = keys
.map(key => obj[key])
.map(
value =>
Array.isArray(value)
? getDeepKeys(value[0])
: typeof value === "object"
? getDeepKeys(value)
: []
)
.reduce((acc, keys) => [...acc, ...keys], []);
return [...keys, ...childKeys];
}
const obj = {
total_count: 6,
incomplete_results: false,
items: [
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
},
{
url: "https://api.github.com/repos/Samhot/GenIHM/issues/6",
id: 293237635,
number: 6,
title: "Rechercher des documents",
user: {
login: "Samhot",
id: 7148311
}
}
]
};
console.log(getDeepKeys(obj));
Which then you would use like map(getDeepKeys). Note that this function assumes all the items in your array have the same schema.
I am trying to translate an object after uploading it but I keep getting 400 Bad Request error.
I am using the forge-api-nodejs-client
here is how my code looks like
var base64 = require('js-base64').Base64;
objectsApi.uploadObject(
bucket.bucketKey,
file.originalname,
file.size,
file.buffer,
{},
oAuth2TwoLegged,
credentials
)
.then(
response => {
const objectDetails = response.body;
// objectId => urn:adsk.objects:os.object:d62db090-0c47-11e8-9a36-7bd06cedf058/Pawn.stl
const job = {
input: {
urn: base64.encode(objectDetails.objectId)
},
output: {
formats: [
{
type: "obj"
}
]
}
};
derivativesApi
.translate(job, {}, oAuth2TwoLegged, credentials)
.then(
data => {
res.send(data);
},
err => {
// it fails here with 400 status error
res.send(err);
}
);
},
err => {
res.send(err);
}
);
my job object looks like this:
{
input:{
urn: 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6ZDYyZGIwOTAtMGM0Ny0xMWU4LTlhMzYtN2JkMDZjZWRmMDU4L1Bhd24uc3Rs'
},
output: {
formats: [
type: "obj"
]
}
}
the response
{
statusCode: 400,
statusMessage: "Bad Request"
}
I have also a tutorial using the Forge NPM to do the whole process of creating bucket to upload file and translate it. I think the part you are having problems with is the uploading part
Check this https://github.com/jaimerosales/modelderivative-nodejs-tutorial/blob/master/uploader.js#L145
Your payload is incorrect, it should look like below:
{
input: {
urn: "...place your design url here ..."
},
output:{
force: false, // true if you want to force regenerate the obj, after new model upload for ex (optional)
formats: [{
type: 'obj',
advanced: {
modelGuid: "...", // model GUID, required
objectIds: [-1] // array of dbIds to export, required. Pass [-1] to export full model, or specific dbIds ex: [49, 56, ...]
}
}],
destination: {
region: 'us' // default, optional can be ['us', 'emea']
}
}
})
You need to perform additional API call to retrieve the model GUID: see GET :urn/metadata for more details
i could not able to parse my nested json data and i tried in many ways but i could not succeed. any help is appreciated.
Here is my json output looks like:
[
{
"task": {
"locator": "FGWESD",
"subtask": [
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
},
{
"work": {
"number": "1145",
"id": "0",
"status": true,
"gate": "N\/A",
},
"sequenceNumber": "0",
"id": "0"
}
],
"connectTime": "0",
"id": "0"
}
}
]
Here is my model:
Ext.define('MyApp.model.MyModel',{
extend:'Ext.data.Model',
xtype:'myModel',
config:{
fields:[
{name:'number',mapping:'work.number'},
{name:'id',mapping:'work.id'},
{name:'locator',mapping:'task.locator'},
{name:'gate',mapping:'work.gate'}
]
}
});
Here is the store:
Ext.define('MyApp.store.StoreList', {
extend:'Ext.data.Store',
config:{
model:'MyApp.model.MyModel',
storeId: 'id_Store',
// added the url dynamically inside the controller
proxy:{
type:'ajax',
reader:
{
type:"json",
rootProperty: 'subtask'
},
method: 'POST',
actionMethods: {
create : 'POST',
read : 'POST', // by default GET
update : 'POST',
destroy: 'POST'
},
headers :{
"Content-Type" :'application/xml',
'Accept':'application/json'
}
}
}
});
Here is my controller code :
Ext.define('MyApp.controller.LoginController', {
extend: 'Ext.app.Controller',
requires: ['Ext.data.proxy.Rest'],
config: {
// My code is too long to add here so am adding store loading when user taps login button
},
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
var url = 'http://localhost:8080/apps';
segmentStore.getProxy().setUrl(url.trim());
segmentStore.load({
scope:this,
callback: function(records, operation, success){
if(success){
console.log('records: ',records);
console.log('records: '+records.length); // prints here 1
console.log('locator: '+records[0].getData().locator);
// prints FGWESD
console.log('locator: '+records[0].getData().number);
//prints undefined
//
}
}
}
)
},
});
Can any one please help me out. how can i get Values of number, gate, id and status?
What are the necessary changes have to be made in model, store and controller ?
Please help me out in resolving ? Thanks.
As I wrote in a comment, I don't think you can achieve that without manually parsing the data and loading it to the store. So the getDetails function should look like this:
getDetails: function(){
var segmentStore = Ext.create('MyApp.store.StoreList');
Ext.Ajax.request({
url: 'http://localhost:8080/apps',
success: function(response){
var responseObj = Ext.decode(response.responseText);
var task = responseObj[0].task;
var locator = task.locator;
var subtasks = [];
Ext.each(task.subtask, function(subtask) {
subtasks.push({
number: subtask.work.number,
id: subtask.work.id,
gate: subtask.work.gate,
locator: locator
});
});
segmentStore.setData(subtasks);
}
});
}
Also, when using this method you should remove the mapping from your model, and you can get rid of the proxy definition of the store. Also, I'm not sure why you want to create the store in the "getDetails" and not define it in the 'stores' config of the controller, but maybe you have your reasons..
I didn't run the code, so there maybe errors, but I hope you get the idea.
I think the root property of your store should be:
rootProperty: 'task.subtask'
children: [
{
name:'Basic Ext Layouts',
expanded: false,
children:[
{
name:'Absolute',
id:'absolute',
leaf:true,
},{
...
}]
}]
Is it possible to change children to mydata?
Is it possible to change children to mydata?
Yes. Setup treestore's proxy to use reader with root config set to 'mydata':
var store = Ext.create('Ext.data.TreeStore', {
model: 'MyModel',
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'mydata' // << this is required
}
},
root: {
myData: [
{
name:'Basic Ext Layouts',
Here is working example.
JSON format is merely a String in javascript's point of view. So you could manipulate the JSON string with associated method.
JSON.
// The original
obj = {
children: [
{
name:'Basic Ext Layouts',
expanded: false,
children:[
{
name:'Absolute',
id:'absolute',
leaf:true,
}]
}]
}
// Transfer the object to a JSON string
var jsonstr = JSON.stringify(obj);
// HERE you do the transform
var new_jsonstr = jsonstr.replace('"children"', '"mydata"');
// You probably want to parse the altered string later
var new_obj = JSON.parse(new_jsonstr);