I am facing a problem. I have this json log
{
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
I need to get all field inside "log" key. These fields will be increased, so I need to get all fields inside log dynamically. I am using this code to parse json, but the output is this. Maybe someone can help me? Thanks.
const readFile = require("fs").readFile;
readFile("log.json", (err, data) => {
if (err) throw err;
const log = JSON.parse(data);
console.log(log);
});
Output:
{
log: 'Log Info : { "datetime" : "datetime", "field1" : "value1", "
field2" : "value2", "field3" : "value3", "field4" : "value4", "field5" :
"value5", "field6" : "value6", "field7" : "value7", "field8" : "value8"
, "field9" : "value9", "field10" : "value10", "field11" : "value11"}\n',
stream: 'stdout',
kubernetes: {
pod_name: 'pod_name',
namespace_name: 'namespace_name',
pod_id: 'pod_id',
host: 'host',
container_name: 'container_name',
docker_id: 'docker_id',
container_hash: 'container_hash',
container_image: 'container_image'
}
}
You need to JSON.parse also the "inner" json (after you clean it from the prefix)
var obj = {
"log": "Log Info : { \"datetime\" : \"datetime\", \"field1\" : \"value1\", \"field2\" : \"value2\", \"field3\" : \"value3\", \"field4\" : \"value4\", \"field5\" : \"value5\", \"field6\" : \"value6\", \"field7\" : \"value7\", \"field8\" : \"value8\", \"field9\" : \"value9\", \"field10\" : \"value10\", \"field11\" : \"value11\"}\n",
"stream": "stdout",
"kubernetes": {
"pod_name": "pod_name",
"namespace_name": "namespace_name",
"pod_id": "pod_id",
"host": "host",
"container_name": "container_name",
"docker_id": "docker_id",
"container_hash": "container_hash",
"container_image": "container_image"
}
}
var str = (obj.log).substring(obj.log.indexOf(':') + 1);
//console.log(str)
var result = JSON.parse(str);
console.log(result)
Related
I need to do a post request using a JSON file. The JSON is currently looking like this:
{
"compositeRequest" : [{
// Account
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Account",
"referenceId" : "refAccount",
"body" : {
"Name" : req.body.accName
}
},{
// Contact
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Contact",
"referenceId" : "refContact",
"body" : {
"LastName" : req.body.conLastName,
"AccountId" : "#{refAccount.id}"
}
},{
// Order
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/Order",
"referenceId" : "refOrder",
"body" : {
"AccountId" : "#{refAccount.id}",
"Pricebook2Id" : PBResult.records[0].Id,
"EffectiveDate" : date,
"Status" : "Draft"
}
},{
// OrderItem
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/OrderItem",
"referenceId" : "refOrderItem",
"body" : {
"Product2Id" : req.params.productId,
"OrderId" : "#{refOrder.id}",
"Quantity" : req.body.itemQuantity,
"PricebookEntryId" : entryResult.records[0].Id,
"UnitPrice" : entryResult.records[0].UnitPrice,
"blng__BillableUnitPrice__c": entryResult.records[0].UnitPrice,
"SBQQ__ChargeType__c": prodResult.records[0].SBQQ__ChargeType__c,
"blng__TaxRule__c": prodResult.records[0].blng__TaxRule__c,
"blng__BillingRule__c": prodResult.records[0].blng__BillingRule__c,
"blng__RevenueRecognitionRule__c": prodResult.records[0].blng__RevenueRecognitionRule__c,
"ServiceDate": date,
"blng__LastChargeToDate__c": date
}
}
]
}
I want to generate more OrderItem objects(indicated in the comment) based on the size of an array, how can I do this? I already have the data that I need to add on the body. Is it possible to create a function to create another OrderItem, and place it after the already existing one (it would even be better if I was going to create the first OrderItem from zero).
Thanks in advance.
If you want to add something to an object, you have to use
Object.assign(myObject, data);
If you want to add something to an array, you have to use:
myArray.push(data);
As I donĀ“t really understand the structure of your data construct, I just try to refer to // OrderItem, which you marked. In this case it would be something like:
let newOrderItem = {
// OrderItem
"method" : "POST",
"url" : "/services/data/v52.0/sobjects/OrderItem",
"referenceId" : "refOrderItem",
"body" : {
"Product2Id" : req.params.productId,
"OrderId" : "#{refOrder.id}",
"Quantity" : req.body.itemQuantity,
"PricebookEntryId" : entryResult.records[0].Id,
"UnitPrice" : entryResult.records[0].UnitPrice,
"blng__BillableUnitPrice__c": entryResult.records[0].UnitPrice,
"SBQQ__ChargeType__c": prodResult.records[0].SBQQ__ChargeType__c,
"blng__TaxRule__c": prodResult.records[0].blng__TaxRule__c,
"blng__BillingRule__c": prodResult.records[0].blng__BillingRule__c,
"blng__RevenueRecognitionRule__c": prodResult.records[0].blng__RevenueRecognitionRule__c,
"ServiceDate": date,
"blng__LastChargeToDate__c": date
}
yourObject.compositeRequest.push(newOrderItem)
So, I have a https function, which when triggered, needs to read the current server time and get the list of items that have a target_date which is lesser than the current time. Once it gets those list of items, those respective items need to be updated by setting its 'status' value to 'completed'. I have written the function but it is throwing an error. Can you please help me fix it?
exports.checkCampaignDate = functions.https.onRequest((request, response) => {
const current_time = Date.now();
console.log("current time", current_time);
var targetRef = admin.database().ref('/Fund');
console.log("target ref", targetRef);
targetRef.orderByChild("time_left").endAt(current_time).once("value", function(snapshot) {
const artcall_list = snapshot.val();
const artcall_id = snapshot.key;
snapshot.forEach((artcallSnap) => {
console.log("Artcall Snap", artcallSnap.val());
artcallSnap.child("status").set("completed");
});
console.log("This is the list of artcalls that have this same date", artcall_list);
console.log("This is the artcall id:", artcall_id);
// do some stuff once
});
return null;
});
My database:
"Fund" : {
"-LEEy7uxXEeI4AJuePoB" : {
"amount_funded" : 5200,
"artist_name" : "Sean Roldan and Friends",
"genre" : "Indian Blues and Jazz",
"image_url" : "https://firebasestorage.googleapis.com/v0/b/artcall-f8f1a.appspot.com/o/profile_images%2Fthumbs%2Fseanroldan.jpg?alt=media&token=6414d8d6-e8a8-487e-baf3-0d36d017a205",
"percent_funded" : 0.29714285714285715,
"perf_location" : "Chennai",
"reward_amt" : 6000,
"target_amount" : 1750000,
"target_date" : 1566568176731,
"time_left" : 1566568176731,
"total_backers" : 1
"status" : "incomplete"
},
"-asdffdsa123" : {
"amount_funded" : 0,
"artist_name" : "Agam",
"genre" : "Rock",
"image_url" : "default",
"percent_funded" : 0,
"perf_location" : "Chennai",
"target_amount" : 1300000,
"target_amt" : 1300000,
"target_date" : 1566568176731,
"time_left" : 1566568176731,
"total_backers" : 0
"status" : "incomplete"
}
},
Error:
TypeError: artcallSnap.child(...).set is not a function
at snapshot.forEach (/user_code/index.js:311:36)
at /user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4255:20
at /user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:3669:24
at LLRBNode.inorderTraversal (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:2606:13)
at SortedMap.inorderTraversal (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:3052:27)
at ChildrenNode.forEachChild (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:3668:24)
at DataSnapshot.forEach (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4254:31)
at /user_code/index.js:309:12
at onceCallback (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4843:51)
at /user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:4465:22
at exceptionGuard (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:691:9)
at EventList.raise (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:9727:17)
at EventQueue.raiseQueuedEventsMatchingPredicate_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:9681:41)
at EventQueue.raiseEventsForChangedPath (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:9665:14)
at Repo.onDataUpdate_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:12770:26)
at PersistentConnection.onDataPush_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:12070:18)
at PersistentConnection.onDataMessage_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:12064:18)
at Connection.onDataMessage_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:11341:14)
at Connection.onPrimaryMessageReceived_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:11335:18)
at WebSocketConnection.onMessage (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:11236:27)
at WebSocketConnection.appendFrame_ (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:10841:18)
at WebSocketConnection.handleIncomingFrame (/user_code/node_modules/firebase-admin/node_modules/#firebase/database/dist/index.node.cjs.js:10891:22)
artcallSnap is a DataSnapshot, which doesn't have a set() method. To get the Reference from a snapshot, use its ref property. So:
artcallSnap.ref.child("status").set("completed")
My attempts at retrieving the value of a firebase record are failing. My JSON is as follows:
{
"accounts" : {
"-KRPSyO4B48IpBnHBTYg" : {
"dateCreated" : "",
"email" : "",
"provider" : "",
"userId" : ""
}
},
"products" : {
"-KUKRafaNurpFhGF4jQa" : {
"name" : ""
}
},
"total" : 1
}
I'm trying to return the value of "total". Here's the latest attampt:
var totals = firebase.database().ref('total').once('value', function(products) {});
$scope.totalPosts = totals;
and my HTML:
<div class="card" ng-controller="myController">{{totalPosts}}</div>
All I'm getting is an empty {}. What am I doing wrong?
Thanks in advance!
Firebase queries are asynchronous, try this.
firebase.database().ref('total').once('value', function(products) {
$scope.totalPosts = products.val();
});
Read and write Data
How to check "no_cover" value in thumbnail[0] and replace it to asset/sss.jpg for show listpage
I try to set <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html ,this show only thumbnail[0] is http://xxx.jpg, http://xxx.jpg , ,But I have no idea to set "no_cover"
myjson
" DOCSET":{
"DOC":[
{
"LINKS":{
"thumbnail":"http://yyy.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"http://xxx.jpg",
"thumbnail":"http://....jpg"}
}],
"DOC":[
{
"LINKS":{
"thumbnail":"no_cover", <<<<
"thumbnail":"http://....jpg"}
}]
}
EDIT - HOW YOUR JSON SHOULD LOOK
Since I (ivaro18) believe you wrote your JSON by hand and did not copy a response object. Let me show you what valid JSON looks like:
{
"DOCSET" : [
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "http://.....jpg"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
},
{
"DOC" : {
"LINKS" : [
{
"thumbnail" : "no_cover"
},
{
"thumbnail" : "http://.....jpg"
}
]
}
}
]
}
END OF EDIT
listpage.html
<ion-list>
<ion-item *ngFor="let item of foundRepos">
<ion-thumbnail item-left >
<img src="{{item.LINKS.thumbnail[0]}}"> <!--I have no idea to set it -->
</ion-thumbnail>
</ion-list>
list.page.ts
this.http.get("my_url")
.subscribe(data =>{
this.foundRepos = data.json().DOCSET.DOC;
},error=>{
err => console.error(err),
() => console.log('getRepos completed')
);
So, first of all your JSON you've posted was invalid. edited your question with what it probably is (since you are printing it as you say)
What I understand from your problem is the following, you have <img src="{{item.LINKS.thumbnail[0]}}"> but this throws a 404 when no_cover is returned, that's why, when item.LINKS.thumbnail[0] is equal to 'no_cover' you want to show the image assets/sss.jpg
So, how can we use this to show 'assets/sss.jpg' instead of 'no_cover'? It's called the Elvis operator ( ? : )
Let's assume the following construction for an if-statement:
if(expression) {
result = whenExpressionIsTrue
} else {
result = whenExpressionIsFalse
}
Which we can rewrite with the Elvis operator like this:
result = someExpression ? whenExpressionIsTrue : whenExpressionIsFalse
So, let's check out your problem, how can we do this with an if-statement?
if(item.LINKS.thumbnail[0] == 'no_cover') {
someVariable = 'assets/sss.jpg';
} else {
someVariable == item.LINKS.thumbnail[0];
}
Now shorten it with the Elvis operator:
someVariable = item.LINKS.thumbnail[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnail[0];
Now this can be used in your HTML like so:
<img
[src]="item.LINKS.thumbnails[0] == 'no_cover' ? 'assets/sss.jpg' : item.LINKS.thumbnails[0]"
/>
im building an gallery app and i need it to be in tree format , im using the jstree extension to build it , and i need the json to be in this format:
$(function () {
$("#demo1").jstree({
"json_data" : {
"data" : [
{
"data" : "A node",
"metadata" : { id : 23 },
"children" : [ "Child 1", "A Child 2" ]
},
{
"attr" : { "id" : "li.node.id1" },
"data" : {
"title" : "Long format demo",
"attr" : { "href" : "#" }
}
}
]
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) { alert(data.rslt.obj.data("id")); });
});
and im using this database:
categorys:
id
name
id_father
products:
id
name
price
category_id
please help me guys , >_< , im using an MVC structure in my project and its possible to do things like foreach(modelinstance as model) ...
help i realy need it and i have no idea how to build it
This is the function that I use, youll need CNestedSetBehavior in your model though, I recomend this way of setting up hierarquical data, as it is much faster to retrieve:
protected function formatJstree(){
$categories = $this->descendants()->findAll();
$level=0;
$parent = 0;
$data = array();
foreach( $categories as $n => $category )
{
$node = array(
'data'=> "{$category->title}",
'attr'=>array('id'=>"category_id_{$category->category_id}")
);
if($category->level == $level){
$data[$parent]["children"][] = $node;
}
else if($level != 0 && $category->level > $level){
if(!isset($data[$n]["children"])){
$data[$n]["children"] = array();
}
$data[$parent]["children"][] = $node;
}
else
{
$data[] = $node;
$parent = $n;
}
$level=$category->level;
}
return $data;
}