JSON.parse & JSON.stringify handling long integers as strings - javascript

I have the problem, that I need to parse long integers in my API. Since I don't do anything arithmetically, it is the easiest to handle them as Strings. I tried Bignumber.js, but it starts complaining if numbers are longer than 15 characters. Unfortunately I have to handle them as well.
Since I don't do anything arithmetically with it and actually even store those numbers as String I would like a JSON Parser that parses too big numbers as Strings and is capable of also treat them as numbers in JSON.stringify.
I tried the stringify with a replacer function, but I could not get rid of the quotes around my number.
I also did not find a library, that just takes care of this issue.
Edit / Clarification
I want my big number to be a String in javascript, but a number in JSON (after JSON.stringify)
e.g. Object in Javascript
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var objString = JSON.stringify(myObj)
Now my objString should be
{id: 89074987798719283473}
And NOT
{id: "89074987798719283473"}

If you absolutely must do this and really can't find a better place to handle this, then remember that JSON is just a string, and all the tools for string manipulation can be brought to bear on this problem. So you could do something like:
var myObj = {
id: "89074987798719283473" // <-- String within javascript
}
var json = JSON.stringify(myObj); // this is {"id":"89074987798719283473"}
var numberJson = json.replace(/"id":"(\d+)"/,'"id":$1'); // this is now {"id":89074987798719283473}
console.log(numberJson);
Of course this is hacky and error prone as you have to be very careful about what you are matching (you might have other properties called id nested in your json that you don't want manipulated). If you wanted to make it a little more robust, you could append something the end of your id before you stringify to make it easier to find and replace it in the string.

Related

Convert JSON with objects and arrays to String

I have a JSON object which looks like this:
{
files: ['test.mp4'],
name: ['testFile'],
hints: ['%YES%_%MAYBE%_%NO%']
}
And I need to convert it to a String so the output looks like this:
[{files=test, name=testFile, hints= %YES%_%MAYBE%_%NO%}]
Is this possible to achieve in Node JS? Thanks
I tried the following:
var x = {
files: ['test.mp4'],
name: ['testFile'],
hints: ['%YES%_%MAYBE%_%NO%']
}
console.log(JSON.stringify(x));
But the output looks like this:
{"files":["test.mp4"],"name":["testFile"],"hints":["%YES%_%MAYBE%_%NO%"]}
Still with the square brackets. I may not 100% know the keys and values in the object above.
Try
JSON.stringify(obj)
then you get a string with quotes etc.
JavaScript has JSON.stringify() method which can convert an object into string:
var x = {
files: ['test.mp4'],
name: ['testFile'],
hints: ['%YES%_%MAYBE%_%NO%']
}
console.log(JSON.stringify(x));
// result: '{"files":["test.mp4"],"name":["testFile"],"hints":["%YES%_%MAYBE%_%NO%"]}'
This will result in a string which can be transformed back to JS object with JSON.parse() method. If you still want to remove all brackets and quotes, you can simply use JavaScript's replace() method (replacing characters [, ], and " with empty string), but this will replace those characters in all your values (if any) and will result in (sort of) non-reusable string.
TL;DR Don't do this unless you absolutely have to (ie. you're dealing with a messed up API written by someone else that must have the data in this format)
If you want exactly the format listed in your question, then you're going to have to write your own stringify function that recursively walks through the object you pass to it and applies whatever rules you want to use. You will have to consider all the possible permutations of your object and spell out those rules.
For example, you've converted arrays with single elements in the initial object into strings - what happens if there is more than one element in the array? Should it be delimited by a comma or some other character? Should we just throw away elements after the first?
And once you've written the stringify function, you'll also have to write the corresponding parse function to reverse it. And it should be mentioned that in your example, you're throwing away information (eg. the file extension on the .mp4 file) - how are you going to handle that?
A much, much better way to approach this would be to do what other people have suggested here: use JSON.stringify and rewrite your code to use standard JSON objects. Why? Because the format is well documented and well understood and because the functions to convert are well tested. You will save yourself a whole lot of time and pain if you don't try to reinvent the wheel here.

converting 'malformed' java json object to javascript

I have a Java JSON Object, its format is [{a=b}], I am trying to pass this object into javascript as a JSON object but its missing " on both the key and value as well as having "=" instead of ":"
Is there a simple way of converting this JAVA JSON object to be consumable by different services?
Parsing is proving to be very complicated as the actual JSON is nested and the lack of quotations and the lacking of indications for nestedness.
Sample of 'JSON' data:
[{wwnType=Virtual, serialNumberType=Virtual, connections=[], modified=2016-10-29T19:00:04.457Z, macType=Virtual, category=server-profile-templates, serverHardwareTypeUri=/rest/server-hardware-types/32006464-D3C6-4B4E-8328-47A193C6116C, bios={overriddenSettings=[], manageBios=false}, firmware={firmwareBaselineUri=null, manageFirmware=false, forceInstallFirmware=false, firmwareInstallType=null}, boot={manageBoot=true, order=[CD, Floppy, USB, HardDisk, PXE]}, hideUnusedFlexNics=true, bootMode=null, state=null, affinity=Bay, localStorage={controllers=[]}, type=ServerProfileTemplateV1, status=OK, description=, eTag=1477767604457/1, serverProfileDescription=test, name=test, created=2016-10-29T19:00:04.428Z, enclosureGroupUri=/rest/enclosure-groups/e989621b-930e-40e7-9db0-a6ddbf841709, uri=/rest/server-profile-templates/db1dbdcc-4237-4452-acc3-cf9dfdc75365, sanStorage={manageSanStorage=false, volumeAttachments=[]}}]
Thanks
It's not going to be simple. However, I think you can do this without writing a full-fledged parser, as long as you're willing to write a tokenizer, or lexical analyzer, to break your input string into tokens. The basic plan could be something like:
Convert your input into a list of tokens. I don't know what the format of your input is, so you'll need to do your own analysis. A token would be something like a single character [, ], {, }, comma, =; or an identifier (a or b in your example, but I don't know what the possible valid formats are); or, maybe, a string literal in quotes, or a numeric literal, depending on what your needs are.
Go through the string and replace the tokens you need to. Based on your example, I'd say that after a {: if the first token after that is an identifier, put it in quotes; if the second token after that is =, change it to :; if the third token after that is an identifier, put it in quotes. The same could be true after a comma, but you'll need to keep track of whether the comma is a separator for a list of key-value pairs in an object, or a list of values in an array. For that, you may need to keep a stack that you push whenever you see [ or {, and pop whenever you see } or ], so that you know whether you're inside an object or an array.
After you're done replacing everything, concatenate the tokens back together. The result should be a well-formed JSON object.
This is just a rough outline, since I really don't know all your requirements. You'll probably have to adapt this answer to meet your exact needs. But I hope this helps as a general idea of how you could approach the problem.
Sorry, I don't think there's a simpler answer, except that you might want to look into parser generators (see Yacc equivalent for Java). I haven't actually looked at any in Java, so I don't know how simple they are to use. Please don't try to solve the whole thing with regexes. (Regexes will be useful for breaking your string into tokens, but trying to do more than that with regexes is likely to produce nothing but migraine.)
I think isn't json object. json object should be like this.
Example:
JSONObject obj = new JSONObject();
obj.put("a", "b");
obj.put("name", "your name");
Output: {"a": "b", "name":"your name"}
Passing into javascript
var obj = '{"a": "b", "name":"your name"}',
var json = JSON.parse(obj);

Variable in JSON

I don't have much experience with JSON, I want to know if something like this is possible.
{
"variable": "A really long value that will take up a lot of space if repeated",
"array": [variable, variable, variable]
}
Obviously that isn't valid, but I want to know if there is a way to do this. I tried using "variable" but of course that just sets the array item to the string "variable". The reason I want to do this is I need to repeat long values in a multidimensional array, which takes up a lot of space.
Thanks.
If you are willing to do some post-processing on the JSON after parsing it, then you can use a token value in your array, and replace the token after parsing with the variable. Example:
{
"variable": "A really long value",
"array": ["variable", "variable", "variable"]
}
Then, in your code that parses:
var obj = JSON.parse(str);
for (var i=0; i<obj.array.length; i++)
{
obj.array[i] = obj[obj.array[i]];
}
Are you worried about space in the output, or in the object created from the JSON? In the latter case, it's likely that the string values will be coalesced when the parsing happens.
If you're concerned about the size of the JSON, then you'll probably either want to change to another format, or de-duplicate the strings in the JSON.
You could add an object to your JSON data that maps ID numbers to strings, then use the IDs to represent te strings.
There is no way to do this in pure JSON (full spec here).
If you wanted to do something like that you might want to look into templating tools such as Handlebars
you will get your answer here jason tutorial for beginners
example:
var data={
"firstName":"Ray",
"lastName":"Villalobos",
"joined":2012
};

How to fetch comma separated values from mentioned string

I want to fetch comma separated IDs and types from below string.
I tried through split but that requires multiple split to fetch desired result.
Please suggest an efficient way to fetch desired output like like 1234,4321 using js/jquery.
var tempString=
'[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"},
{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
To get "1234,4321", you can do
var ids = tempString.map(function(v){return v.id}).join(',');
If you want to be compatible with IE8, then you can do
var ids = $.map(tempString, function(v){return v.id}).join(',');
Following question edit :
If tempString isn't an array but really a JSON string, then you'd do
var ids = $.map(JSON.parse(tempString), function(v){return v.id}).join(',');
As pointed out, that's not a String in your example. Some quotation marks went missing.
At any rate, look into #dystroy's answer, but I think you are dealing with JSON objects, and you should probably be useing a json parser (or even javascripts raw eval if you must) and then fetch your components as object properties and arrays.
Check out jquery's parseJSON
You should use any Javascript parser api for JSON to decode the given string into keys and subsequent values. As mentioned by 'Miquel', jQuery has one
first off what you have above isn't a string, it is an array of objects.
BUT
if it were a string (like so )
var tempString = '[{"id":"1234","desc":"description","status":"activated","type":"type","name":"NAME"}]
[{"id":"4321","desc":"description1","status":"inactivated","type":"type","name":"NAME1"}]';
Then you would want to use something like .match();
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match
var IDs = tempString.match(/([0-9]+)/gi);

Javascript parse innerhtml

I have a HTML page full of data separated by commas and each row ends in a (br /) tag. In Javascript I can get this from the DOM by asking for the innerHTML of the element containing the data.
My question is how to parse the innerHTML to get the data out from between the commas and start on the next line when it hits the (br /) tag?
You can probably ignore the rest as that is my question above.
When I parse each line I will start a new object and put the data into it. I'm just not sure what to do with the innerHTML!
I did put the data through a CSVtoarray function I found but ended up with an array of one large array instead of an array of arrays for each line. I can work my way through this array creating objects from the data along the way but turning the innerHTML into a single array seems an unnecessary step when I could parse the data straight into object.
The data is put there via AJAX. I can change the format that the data comes in. As I said I have it separating data with commas and (br /) tag at the end of the line. I do not know if this is stupid or not.
So, you want to csv-parse a file where newlines are indicated with <br /> instead of \n? Just use that separator in your CSV-Parser then. Simple version:
text.split("<br />".map(function(line){ return line.split(","); })
You could also split by regular expressions, like
text.split(/\s*<br ?\/>\s*/)...
If you really habe the CSV data in a DOM, you could remove all the br-element and use the remaining (text) nodes as the lines-array.
You mention that you have control over the data you're getting via AJAX, and you're right that your current approach is not the best idea. First off, you should never try to parse HTML on your own, even if you think it's "simple" – different browsers will give you different innerHTML for the exact same content. Instead, use the DOM to find the information you're looking for.
That said, the correct approach here is just to return a JSON object from the server; you'll then have direct access to your data. Nearly every server-side language has some kind of facility to output JSON, and JavaScript can parse the JSON string natively1 with JSON.parse().
From the server, return:
{items: [
{ id: 0, name: '...' },
{ id: 1, name: '...' },
...
]}
On the client (assuming jQuery),
$.getJSON('/path-to-script/', function(d) {
for (var i = 0; i < d.items.length; i++) {
d.items[i].id;
}
});
1 - in modern browsers
You could simply do this if you just want to "get the data out from between the commas":
yourElem.innerHTML = yourElem.innerHTML.split(",").join("");
Or if you just want an array of lines:
var lines = yourElem.innerHTML.split(",");
That'll return an array of lines with <br> elements intact. It's not clear if that's what you want, though.

Categories