I have the following JSON, I want add commas in between the numbers, but when ever I do that the JSON fails. My workign version of the code can be seen in the fiddle link below
FIDDLE
I want to change this 11488897 to 11,488,897
Is this possible to do? How can this be done?
thanks for your help
[{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}]
If you want to preserve commas, you just need to use strings:
"data": ["48,353,330","38,079,817","37,130,929","1,957,317"]
Whether that's a good idea or not is another story. Typically you'd want your JSON returned by the server to include raw (i.e., integer) data, and then just format it however you want when you're actually using it. That way the same RPC endpoint can be used to fetch data for use in a chart or for any other purpose that might arise later on.
try this:
var data = [{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}];
data.forEach(function(obj) {
obj.data = obj.data.map(function(item) {
if (typeof item == 'number') {
return item.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return item;
}
});
});
alert(JSON.stringify(data, true, 4));
I don't know if it's cross-browser but if you do this
var number = 11488897;
number = number.toLocaleString('en');
You'll get the number (string) with commas on decimals
Related
I'm trying to get the latest records, grouped by the field groupId, which is a String like "group_a".
I followed the accepted answer of this question, but I've got the following error message:
Fielddata is disabled on text fields by default. Set fielddata=true on [your_field_name] in order to load fielddata in memory by uninverting the inverted index. Note that this can however use significant memory.
In the Elasticsearch docs is written:
Before you enable fielddata, consider why you are using a text field for aggregations, sorting, or in a script. It usually doesn’t make sense to do so.
I'm using a text field, because groupId is a String. Does it make sense to set fielddata: true if I want to group by it?
Or are there alternatives?
Using "field": "groupId.keyword" (suggested here) didn't work for me.
Thanks in advance!
The suggest answer with .keyword is the correct one.
{
"aggs": {
"group": {
"terms": {
"field": "groupId.raw"
},
"aggs": {
"group_docs": {
"top_hits": {
"size": 1,
"sort": [
{
"timestamp (or wathever you want to sort)": {
"order": "desc"
}
}
]
}
}
}
}
}
}
with a mapping like that:
"groupId": {
"type": "text",
"fields": {
"raw": {
"type": "keyword"
}
}
}
The server I'm working with changed the REST format from plain JSON:
{
"removedVertices": [
{
"id": "1",
"info": {
"host": "myhost",
"port": "1111"
},
"name": "Roy",
"type": "Worker"
}
],
"id": "2",
"time": 1481183401573
}
To Jackson format:
{
"removedVertices": [
"java.util.ArrayList",
[
{
"id": "1",
"info": [
"java.util.HashMap",
{
"host": "myhost",
"port": "1111"
}
]
"name": "Roy",
"type": "Worker",
}
]
"id": "2",
"time": 1482392323858
}
How can I parse it the way it was before in Angular/Javascript?
Assuming only arrays are affected, I would use underscore.js and write a recursive function to remove the Jackson type.
function jackson2json(input) {
return _.mapObject(input, function(val, key) {
if (_.isArray(val) && val.length > 1) {
// discard the Jackson type and keep the 2nd element of the array
return val[1];
}
else if (_.isObject(val)) {
// apply the transformation recursively
return jackson2json(val);
}
else {
// keep the value unchanged (i.e. primitive types)
return val;
}
});
}
If the api should be restful, then the server should not return none plain json results. I think the server site need to fix that.
I think it is because the server enabled the Polymorphic Type Handling feature.
Read Jackson Default Typing for object containing a field of Map and JacksonPolymorphicDeserialization.
Disable the feature and you will get result identical to plain json.
The main difference i see is that in arrays you have an additional string element at index 0.
If you always get the same structure you can do like this:
function jacksonToJson(jackson) {
jackson.removedVertices.splice(0, 1);
jackson.removedVertices.forEach((rmVert) => {
rmVert.info.splice(0, 1);
});
return jackson;
}
I have the following JSON:
{
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]}
}
I want to access "value" of the the array element with "fieldName": "telNum" without using index numbers, because I don't know everytime exactly at which place this telNum element will appear.
What I dream of is something like this:
jsonVarName.responseObject.fields['fieldname'='telNum'].value
Is this even possible in JavaScript?
You can do it like this
var k={
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
}};
value1=k.responseObject.fields.find(
function(i)
{return (i.fieldName=="telNum")}).value;
console.log(value1);
There is JSONPath that lets you write queries just like XPATH does for XML.
$.store.book[*].author the authors of all books in the store
$..author all authors
$.store.* all things in store, which are some books and a red bicycle.
$.store..price the price of everything in the store.
$..book[2] the third book
$..book[(#.length-1)]
$..book[-1:] the last book in order.
$..book[0,1]
$..book[:2] the first two books
$..book[?(#.isbn)] filter all books with isbn number
$..book[?(#.price<10)] filter all books cheapier than 10
$..* All members of JSON structure.
You will have to loop through and find it.
var json = {
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
};
function getValueForFieldName(fieldName){
for(var i=0;i<json.fields.length;i++){
if(json.fields[i].fieldName == fieldName){
return json.fields[i].value;
}
}
return false;
}
console.log(getValueForFieldName("telNum"));
It might be a better option to modify the array into object with fieldName as keys once to avoid using .find over and over again.
fields = Object.assign({}, ...fields.map(field => {
const newField = {};
newField[field.fieldName] = field.value;
return newField;
}
It's not possible.. Native JavaScript has nothing similar to XPATH like in xml to iterate through JSON. You have to loop or use Array.prototype.find() as stated in comments.
It's experimental and supported only Chrome 45+, Safari 7.1+, FF 25+. No IE.
Example can be found here
Clean and easy way to just loop through array.
var json = {
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
}
$(json.responseObject.fields).each(function (i, field) {
if (field.fieldName === "telNum") {
return field.value // break each
}
})
I know this is a very simple and common question; I've already read some Q/A but I can't figure out how to solve my problem.
I have this short json from an AJAX call that execute a SPARQL query:
{
"head": {
"vars": [ "name" , "email" ]
} ,
"results": {
"bindings": [
{
"name": { "type": "literal" , "value": "Name Surname" } ,
"email": { "type": "literal" , "value": "name.surname#email.com" }
}
]
}
}
I'm searching name and email of a single user of the application, so
the result should be always made up of a single element.
What I want to retrieve is the "name" of the user.
I tried something like:
response["name"].value
//or
response[0]["name"]
//or
response.name
but always wrong.
How can I get the name value? Thanks to everyone who will help.
Try this
response.results.bindings[0].name.value
response.results.bindings[0].email.value
Update
Example
You can check out the fiddle created here
http://jsfiddle.net/uqxp4j73/
The code for this is as under
var x='{ "head": { "vars": [ "name" , "email" ] } , "results": { "bindings": [ { "name": { "type": "literal" , "value": "aadil keshwani" } , "email": { "type": "literal" , "value": "name.surname#email.com" } } ] }}';
obj = JSON && JSON.parse(x) || $.parseJSON(x);
console.log(obj);
console.log(obj["results"]["bindings"][0]["name"]["value"]);
alert(obj["results"]["bindings"][0]["name"]["value"]);
Hope this helps :)
In JSON, you always have to provide the full path to the property you like to reach. Assuming you have stored the parsed JSON in variable response, the following paths will get you corresponding value.
response.results.bindings[0].name.value for name
response.results.bindings[0].email.value for email
Recommend you to go through http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ to get basic concepts of JSON.
I wrote the following JavaScript function (part of a larger "class") to help ensure anybody using the object stores attribute values in the "values" property.
function _updateAttributes(attribute, value) {
_attributes[attribute] = { values: { value: value }};
}
It works fine for a flat structure, but falls apart when I start trying to use it for sub-properties.
After running the following code:
myEntity.updateAttribute('name', 'Frankenstein');
myEntity.updateAttribute('name.source', 'John Doe');
I'd like the following structure:
{
"attributes": {
"name": {
"values": {
"value": "Frankenstein"
},
"source": {
"values": {
"value": "JohnDoe"
}
}
}
}
}
Instead, it's coming out like this:
{
"attributes": {
"name": {
"values": {
"value": "Frankenstein"
}
},
"name.source": {
"values": {
"value": "JohnDoe"
}
}
}
}
Is there any clean way to write this JavaScript or will I be faced with splitting out the strings and manually building the structure?
NOTE: I realize even the preferred structure is a little odd, but there's a Java object I'm mapping to that expects this format, so I don't have any options here.
You'll have to parse the string (parse is a bit strong, just a single split('.') with a loop).
But frankly, the cleaner way would simply be:
myEntity.name = {values: 'Frankenstein'};
myEntity.name.source = {values: 'John Doe'};