Convert JSON with objects and arrays to String - javascript

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.

Related

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);

How can I remove dynamic data in string before a value in that string? / using Lodash's _.trimStart with dynamic data?

I'm working urls returned from a server that I have no control over where and sometimes the urls return with extra data at the front.
For instance
sometimes it returns this
https://example.com/image/5119b3905.jpg
and this I can use, but sometimes it will return something like this
https://d1yww.cloudfront.net/9MA=/670x670/example.com/image/5119b3905.jpg
where I'd like to use remove everything before the example.com and to do that I could use something like lodash's _.trimStart method something like
_.trimStart('https://d1yww.cloudfront.net/9MA=/670x670/example.com/image/5119b3905.jpg',
'd1yww.cloudfront.net/9MA=/670x670');
but the d1yww.cloudfront.net/9MA=/670x670' is never static for me to do this and I don't know how to grab the dynamic data to use _.trimStart and I don't see any other useful lodash's methods and I don't know of any vanilla javascript ones.
TLDR: How can I remove dynamic data in string before a value in that string (in this example everything before the example.com)
You don't need lodash to do that
var str = 'https://d1yww.cloudfront.net/9MA=/670x670/example.com/image/5119b3905.jpg'
str.substr(str.indexOf('example.com'))
You could search for a Regular Expression
For Example:
/\/([-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b)\//g
and look for the second match

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

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.

jQuery/JavaScript regex return matched text from string

I am trying to create a fairly complex system for my website. I want to be able to write some pseudo like code and then parse it to make it do something in my back-end.
My data is inside two $.each loops as this is an Object of data with multiple levels to it.
For instance, I want to take a string like this:
"<!this!> == <!PropertyStreetNumber!>"
Then how I would like for the above code to executed is this:
FormData[parentKey][this] == FormData[parentKey]["PropertyStreetNumber"]
Thanks for any help!
Here's some of my code, the code where this would need to go in (see commented area)
http://jsbin.com/liquvetapibu/1/
Is there any restriction not to use regular expressions on JavaScript?
You could do something like this:
var myString = "<!this!> == <!PropertyStreetNumber!>";
var aux = /<!(.*?)!> == <!(.*?)!>/.exec(myString);
The value of aux will be an array with 3 elements:
The string that was tested.
The first element within <! !>
The second element within <! !>
Then it would depend on what the content on each one is: in your example this is an object, while you seem to use PropertyStreetNumber as a string (maybe a typo?). If you want to use it as an object, you will have to use eval() (e.g.: eval(aux[1])) while if you want to use it as a string, you can use it directly (e.g.: aux[2]).
Conceptually, the first thing you would need to do is determine the type of statement you are working with. In this case, a comparison statement. So you need a regex statement to filter this into a "statement type".
Once you do that, you can figure out what the arguments are. So you create a regex to pull out the arguments on each side of the operator.
Next, the strings that represent action code items need to be parsed. The this argument is actually an object, whereas "PropertyStreetNumber" is a string. You've got to be able to determine which is which. Then you can filter that into a function that has been created specifically to handle those statements types.
If at all possible, I would try to avoid the use of eval(). You can get into trouble with it.
you could try with
var beg = str.indexOf("== <!") + 5;
to find the index of the beggining and then slice counting the chars from beginning like
str.slice(beg, -2);
and from there build the rest.
couldnt that work?`

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
};

Categories