I know this is already asked question but i don't get answer from any question previously asked...
My Problem is - Server sends a Array of JSON objects as String and i want to convert the string in to valid JSON array.
Example: Server sends like this
'{
"ts": "3170075",
"eventid": 25,
"oper_minutes": 48577,
"time": "2016-12-02T06:36:36Z",
"lto": "7200000",
"package_name": "XXX",
"timestamp": "1480660593188",
"action_type": "1",
"events": [{
"device_name": 0,
"key_category": 1,
"eventid": 15,
"ts": "2111"
}, {
"power_state": 3,
"reason": 1,
"eventid": 1,
"ts": "2113"
}]
}, {
"ts": "3170084",
"eventid": 25,
"oper_minutes": 48577,
"time": "2016-12-02T06:36:36Z",
"lto": "7200000",
"package_name": "XXXX",
"timestamp": "1480660593218",
"action_type": "1",
"events": [{
"device_name": 0,
"key_category": 1,
"eventid": 15,
"ts": "2111"
}, {
"power_state": 3,
"reason": 1,
"eventid": 1,
"ts": "2113"
}]
}'
I want to convert it into valid array of two objects using pure javascript.
Example:
[{
"ts": "3170075",
"eventid": 25,
"oper_minutes": 48577,
"time": "2016-12-02T06:36:36Z",
"lto": "7200000",
"package_name": "XXX",
"timestamp": "1480660593188",
"action_type": "1",
"events": [{
"device_name": 0,
"key_category": 1,
"eventid": 15,
"ts": "2111"
}, {
"power_state": 3,
"reason": 1,
"eventid": 1,
"ts": "2113"
}]
}, {
"ts": "3170084",
"eventid": 25,
"oper_minutes": 48577,
"time": "2016-12-02T06:36:36Z",
"lto": "7200000",
"package_name": "XXX",
"timestamp": "1480660593218",
"action_type": "1",
"events": [{
"device_name": 0,
"key_category": 1,
"eventid": 15,
"ts": "2111"
}, {
"power_state": 3,
"reason": 1,
"eventid": 1,
"ts": "2113"
}]
}]
I already tried JSON.parse, JSON.stringify, etc
No valid result as expected..
NOTE: This array of objects may be of any size, the server sometimes send 1000 objects and sometimes only 10 but as string. Should not take too much time to process.
Please help, i'm stuck with this for almost a day.. i'm using this in nodeJS so Only pure javaScript or with NPM libraries.
The JSON string you're sending is invalid because it should be encapsulated in [].
You could do :
var str = '{"ts": "3170075","eventid": 25,"oper_minutes": 48577,"time": "2016-12-02T06:36:36Z","lto": "7200000","package_name": "XXX","timestamp": "1480660593188","action_type": "1","events": [{"device_name": 0,"key_category": 1,"eventid": 15,"ts": "2111" }, {"power_state": 3,"reason": 1,"eventid": 1,"ts": "2113" }]}, {"ts": "3170084","eventid": 25,"oper_minutes": 48577,"time": "2016-12-02T06:36:36Z","lto": "7200000","package_name": "XXXX","timestamp": "1480660593218","action_type": "1","events": [{"device_name": 0,"key_category": 1,"eventid": 15,"ts": "2111" }, {"power_state": 3,"reason": 1,"eventid": 1,"ts": "2113"}]}';
var obj = JSON.parse(`[${str}]`);
The errors you get trying to do it manually are because your original String is invalid as posted in your post (because of the newlines).
Related
Hello guys I am currently trying to phrase a json but it's hard for me. The json response is
{
"txs":
{
"lock_time": 0,
"ver": 1,
"size": 372,
"inputs": [
{
"sequence": 4294967295,
"prev_out": {
"spent": true,
"tx_index": 78636642,
"type": 0,
"addr": "1Dihat9Fy1ZDzFCq33LN5M7kzG3Fmi3FbZ",
"value": 61140,
"n": 1,
"script": "76a9148b84711990f82d3cd70013e738787506a2156ebf88ac"
},
"script": "47304402203409c3381b75deac615630125c62af73e959e4e42431397209d0298da272c4b4022011720c0e8ecc8a4d01e1f6210891fe5e65f581473c05f0b15bc38010ca5155610121038b1c61898ba817c0361fb910c001cddf309388f6e156f96de749fdbb1c531f34"
},
{
"sequence": 4294967295,
"prev_out": {
"spent": true,
"tx_index": 78634898,
"type": 0,
"addr": "1Dihat9Fy1ZDzFCq33LN5M7kzG3Fmi3FbZ",
"value": 379950,
"n": 1,
"script": "76a9148b84711990f82d3cd70013e738787506a2156ebf88ac"
},
"script": "473044022051029de181886a8225e78ea8c97fcdff4fdf65bd5479cf4370a8bf38ffd8770002202e788bb00aa4b017249eeefdfcf49cc2e591a7dbb25a1b2a3df924505b7683a50121038b1c61898ba817c0361fb910c001cddf309388f6e156f96de749fdbb1c531f34"
}
,
"doublespend": false,
"time": 1424718521,
"txindex": 78637260,
"vinsz": 2,
"hash": "011931da4d5ef3afde1b043f285b27cec2883b9d77feda71fe67b13341778494",
"voutsz": 2,
"relayedby": "127.0.0.1",
"out": [
{
"addrtaglink": "http://luckyb.it/",
"addrtag": "LuckyBit blue",
"spent": false,
"txindex": 78637260,
"type": 0,
"addr": "1LuckyB5VGzdZLZSBZvw8DR17iiFCpST7L",
"value": 356450,
"n": 0,
"script": "76a914da5dde86d69a5d9dad88763f2df4b048953c7d0488ac"
},
{
"spent": false,
"txindex": 78637260,
"type": 0,
"addr": "1Dihat9Fy1ZDzFCq33LN5M7kzG3Fmi3FbZ",
"value": 74640,
"n": 1,
"script": "76a9148b84711990f82d3cd70013e738787506a2156ebf88ac"
}
]
}
]
}
This json is stored in a variable content.
By let content = JSON.parse(result)
I used
var data = content.txs.inputs.addr
to take out the info from that but it shows nothing, null.
I also tried only content and it works, but it doesn’t work with content.txs.inputs.addr. Can any JavaScript developers help me solve this? I’m facing this type of json for the first time.
The object model for the inputs array don't have any addr property, you need to access the prev_out object property to get the addr value.
You are missing an closing ] in the inputs array, and you need to remove the ] at the end of the json file.
After that you can get the addr property in the next way:
const content = {
"txs":
{
"lock_time": 0,
"ver": 1,
"size": 372,
"inputs": [
{
"sequence": 4294967295,
"prev_out": {
"spent": true,
"tx_index": 78636642,
"type": 0,
"addr": "1Dihat9Fy1ZDzFCq33LN5M7kzG3Fmi3FbZ",
"value": 61140,
"n": 1,
"script": "76a9148b84711990f82d3cd70013e738787506a2156ebf88ac"
},
"script": "47304402203409c3381b75deac615630125c62af73e959e4e42431397209d0298da272c4b4022011720c0e8ecc8a4d01e1f6210891fe5e65f581473c05f0b15bc38010ca5155610121038b1c61898ba817c0361fb910c001cddf309388f6e156f96de749fdbb1c531f34"
},
{
"sequence": 4294967295,
"prev_out": {
"spent": true,
"tx_index": 78634898,
"type": 0,
"addr": "1Dihat9Fy1ZDzFCq33LN5M7kzG3Fmi3FbZ",
"value": 379950,
"n": 1,
"script": "76a9148b84711990f82d3cd70013e738787506a2156ebf88ac"
},
"script": "473044022051029de181886a8225e78ea8c97fcdff4fdf65bd5479cf4370a8bf38ffd8770002202e788bb00aa4b017249eeefdfcf49cc2e591a7dbb25a1b2a3df924505b7683a50121038b1c61898ba817c0361fb910c001cddf309388f6e156f96de749fdbb1c531f34"
}]
,
"doublespend": false,
"time": 1424718521,
"txindex": 78637260,
"vinsz": 2,
"hash": "011931da4d5ef3afde1b043f285b27cec2883b9d77feda71fe67b13341778494",
"voutsz": 2,
"relayedby": "127.0.0.1",
"out": [
{
"addrtaglink": "http://luckyb.it/",
"addrtag": "LuckyBit blue",
"spent": false,
"txindex": 78637260,
"type": 0,
"addr": "1LuckyB5VGzdZLZSBZvw8DR17iiFCpST7L",
"value": 356450,
"n": 0,
"script": "76a914da5dde86d69a5d9dad88763f2df4b048953c7d0488ac"
},
{
"spent": false,
"txindex": 78637260,
"type": 0,
"addr": "1Dihat9Fy1ZDzFCq33LN5M7kzG3Fmi3FbZ",
"value": 74640,
"n": 1,
"script": "76a9148b84711990f82d3cd70013e738787506a2156ebf88ac"
}
]
}
};
// Now you can get the info
content.txs.inputs.forEach(element => {
console.log(element.prev_out.addr);
})
content.txs.inputs is an array. Did you mean var data = content.txs.inputs[0].prev_out.addr;?
You need to go down a couple more steps
inputs is an array, so you need a subscript, then two more levels of keys:
Var data = content.txs.inputs[0].prev_out.addr
Note that there is an addr value in both the inputs elements. Change the subscript to get the other one.
element inputs is an arrray, so you need access each postion in array, you can use for loop for element inputs, access each position such as inputs[0].addr, inputs[1].addr
I have a collection like that:
{
"_id": {
"$oid": "5f54b3333367b91bd09f4485"
},
"products": [
{
"_id": 20,
"name": "Türk Kahvesi",
"price": 8,
"count": 2
},
{
"_id": 22,
"name": "Dibek",
"price": 10,
"count": 2
},
{
"_id": 21,
"name": "Damla Sakızlı T.K.",
"price": 10,
"count": 1
}
],
"deskId": "5f53473611f7490d3c860ccd",
"waiterId": "1",
"deskName": "Ü2",
},
{
"_id": {
"$oid": "5f54af663367b91bd09f4483"
},
"products": [
{
"_id": 20,
"name": "Türk Kahvesi",
"price": 8,
"count": 1
},
{
"_id": 21,
"name": "Damla Sakızlı T.K.",
"price": 10,
"count": 1
},
{
"_id": 22,
"name": "Dibek",
"price": 10,
"count": 1
},
{
"_id": 23,
"name": "Menengiç",
"price": 10,
"count": 1
},
{
"_id": 25,
"name": "Double Espresso",
"price": 15,
"count": 6
}
],
"deskId": "5f53473611f7490d3c860ccd",
"waiterId": "1",
"deskName": "Ü2",
}
And my goal is, getting all data order and group by product._id and show totalPrice(price*count),products.name, _id and totalCount. This is actually to show us a report product by product. If you need any more information, Just ask. Sample result:
{
{
"_id": 20,
"name": "Türk Kahvesi",
"totalCount": 3,
"totalPrice": 24
},
{
"_id": 22,
"name": "Dibek",
"totalCount": 3,
"totalPrice": 30
},
{
"_id": 21,
"name": "Damla Sakızlı T.K.",
"totalCount": 2,
"totalPrice": 20
},
{
"_id": 23,
"name": "Menengiç",
"totalCount": 1,
"totalPrice": 10
},
{
"_id": 25,
"name": "Double Espresso",
"totalCount": 6,
"totalPrice": 90
}
}
We can use aggregate on something. Please help me.
I'm still new to MongoDB, but I think this aggregate pipeline is what you're looking for. That said this is the kind of thing you should research yourself using the documentation, but as long as you understand the thought process you'll learn something so it's all good!
[
{
$unwind: {
path: '$products',
// Here we are seperating each item in the products array of
// the user(I presumed your objects were users, or carts maybe)
// It will now be available to the next stage of the pipeline as
// a singular object for each item in the array,
// see the picture below for how this works practically.
}
},
{
$group: {
// Now we're going to restructure the object to
// center around the id field of the products, and
// at the same time we can add up the total price
// and count of each item.
_id: '$products.id', // This is the selector for the grouping process (in our case it's the id)
item: { $first: '$$ROOT.products' }, // this is me thinking you'll want access to the item in question for each total.
totalCount: { $sum: "$products.count" }, // adds to totalCount EACH $products.count that we have
totalPrice: { $sum: { $multiply: ["$products.price", '$products.count'] } }, // self explanatory
}
}
]
this is what unwind does to your array and object
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
NB I modified/removed some variable names(_id, oid) for practical reasons, you'll have to parse through which ones and this code will most likely not work right away if copy-pasted.
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
when i am using fetch i am getting data in json format. I want to search json via cust_id and return only matching record. please tell me how to do it. I have to show all the credit card the person have.
"objects": [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
var objects= [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
console.log(objects.filter(i=>i['cust_id'] === '12345'))
I hope it helps
var val={
"objects": [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
};
function get(val,custid){
var result;
for(var i=0;i<val.objects.length;i++){
if(val.objects[i].cust_id=custid){
result= val.objects[i];
}
}
return result;
}
console.log(get(val,"1235"));
For multiple records you can take result as array and use array.push to insert in result (function variable) and return the array in end
In the map function of my view I am trying to change a field of a javascript object. Interestingly i can not change a field and than emit that object.
I expect all the name fields if the irem object would be "test". But i can`t change it. Any help would be great..
Map Function
function(doc) {
doc.movieList.forEach(function(item){
item.name = "test";
emit([doc.companyId,item.movieID],item);
});
}
Result
"rows": [
{
"key": [
"147",
"044a30f24e98660a8a8c12d09b1cafb3"
],
"value": {
"categoryID": 4,
"dataModelVersion": 1,
"forSale": false,
"movieID": "044a30f24e98660a8a8c12d09b1cafb3",
"name": "HULK", //This field shoud be "test"
"orderId": 99,
"term": 0,
"visible": true,
"watchCount": 0
}
},
{
"key": [
"147",
"07c3c1bc4ac5d99286ccc54cde06b86a"
],
"value": {
"categoryID": 2,
"dataModelVersion": 1,
"forSale": false,
"movieID": "07c3c1bc4ac5d99286ccc54cde06b86a",
"name": "KACIS-PLANI", //This field shoud be "test"
"orderId": 99,
"term": 0,
"visible": true,
"watchCount": 0
}
},
{
"key": [
"147",
"0c6f28034e39bc94009be0375e2fba2a"
],
"value": {
"categoryID": 8,
"dataModelVersion": 1,
"forSale": false,
"movieID": "0c6f28034e39bc94009be0375e2fba2a",
"name": "YOLA-GELDIK", //This field shoud be "test"
"orderId": 99,
"term": 0,
"visible": true,
"watchCount": 0
}
},
Checking into CouchDB code, the doc provided to the map function is sealed so no modification is allowed over the original object.
You need to copy the original object into a new one in order to modify its attributes.
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