Remove empty {} in JSON - json

I have JSON which is something like this
Var myObj = {{},{'test': '1'}}
I would like to remove the {} so end up like
{'test':'1'}.
How can do this?

This is totally not valid JSON. You'll get an error if you actually try to assign that not-JSON to a variable ("Var" should be lowercase by the way).
You'll need to convert it to a string (actually presumably it is a string already because it's invalid as an object), use a regex to replace the offending invalid JSON, and then convert back to JSON.
var myObjStr = "{{},{'test': '1'}}";
var validMyObjStr = myObjStr.replace(appropriateRegEx, '');
var myObj = eval('(' + validMyObjStr + ')');
If you need it, I can build an appropriate RegEx for you. Just drop a comment. But really, you should probably fix whatever's giving you the invalid JSON in the first place.

Related

Ambiguous format output in nodejs

I am having output in following format as
"[{"a":"a1"},{"a":"a2"}]"
I want to actually extract it in array of json:
[
{
"a":"a1"
},
{
"a":"a2"
}
]
How to convert it?
You have tagged this with Node-RED - so my answer assumes that is the environment you are working in.
If you are passing a message to the Debug node and that is what you see in the Debug sidebar, that indicates your msg.payload is a String with the contents of [{"a":"a1"},{"a":"a2"}] - the Debug sidebar doesn't escape quotes when displaying strings like that.
So you likely already have exactly what you want - it just depends what you want to do with it next.
If you want to access the contents you need to parse it to a JavaScript Object. You can do this by passing your message through a JSON node.
Assuming your input contains the double quotes in the beginning and end, it is not possible to directly JSON.parse() the string.
In your case, you need to remove the first and last character (the double quotes) from your string before parsing it.
const unformattedString = '"[{"a":"a1"},{"a":"a2"}]"'
const formattedString = unformattedString.substr(1, unformattedString.length - 2)
const json = JSON.parse(formattedString)
The variable json now contains your JSON object.
I would suggest a different method which will get your work done without using any third party library.
var a = '[{"a":"a1"},{"a":"a2"}]';
var b = JSON.parse(a);
console.log(b); // b will return [{"a":"a1"},{"a":"a2"}]
Another way which is eval function which is generally not recommended
var d = eval(a);
If you want to use JQuery instead use :
var c = $.parseJSON(a);

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

Cannot Parse Json when escaping double quotes

I've created an application that's reading data from http response. The data comes back as JSON and the JSON string contains backslashes where the double quotes are escaped.
I've tried the example demonstrated here, Android: Parsing JSON string inside of double quotes.
Here's my example:
var data="\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\""
var escapeSlashes = data.replace("\\\"/g", "\"");
It returns like this:
[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]
The code breaks when trying to parse.
var obj = $.parseJSON(escapeSlashes);
Is there another way of handling this other than doing a replace?
Alright, so.. it's really just JSON, escaped several times. Super silly thing to do, but how to solve this?
Let's unescape it several times!
Here we go:
var moo = "\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\"";
// Don't let the backslashes confuse you
// What the string really contains is here:
console.log(moo);
// "[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]"
// That's a JSON string, see the quotes at the ends?
// Let's parse!
var moo2 = JSON.parse(moo);
console.log(moo2);
// [{"FirstName":"John","LastName":"Doe"}]
// Alright, looks like a regular JSON array with one object in it.
// Crack it open!
var moo3 = JSON.parse(moo2);
console.log(moo3);
// Hole cow, we got a JS Object!
// [Object { FirstName="John", LastName="Doe"}]
// Do whatever you want with it now...
Try it out: http://jsfiddle.net/YC6Hx/

AS3: Use the underscore character in a URLVariables variable name

Is it possible to use the underscore character in a URLVariables variable name? For instance, the following code outputs "my%5Fusername=foo" instead of "my_username=foo".
import flash.net.URLVariables;
var variables : URLVariables = new URLVariables("my_username=foo");
trace(variables.toString());
Just as in the trace, the "%5F" shows up instead of the underscore in the request. Is there some way I can get the underscore character to show up instead?
Simply don't use URLVariables class, it's known to do other things wrong too. This URL RFC calls the underscore a special character and puts it in the same category as alphanumeric, saying that no encoding is needed. This RFC calls the part where you'd have the variables as "query" and allocates pchar to it, describing pchar as containing underscore character.
In practice URI containing underscore characters doesn't seem to give problem to browsers or servers, so it's just plain wrong to encode it.
EDIT: from further reading it looks more like that this is rather an undesirable behavior, then a mistake (the URI normalizer would know to revert the encoded underscore to it's original look), still, encoding underscore is the same as encoding letters of English alphabet - wasteful and stupid.
Using a regular expression, you can convert the output to underscore. This method takes advantage of the facts that:
URLRequest's data variable is a generic Object
String is an Object
output of toString() and replace() are String objects 3.
The code:
var url:String = "http://www.[yourDomain].com/test";
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables("my_user_name=f_o_o");
// add some more variables:
variables.exampleSessionId = "test";
variables.example_Session_Id2 = "test2";
// set up the search expression:
var undPatrn:RegExp = /%5f/gi;
trace("Without '_': " + variables.toString());
trace("With '_': " + variables.toString().replace(undPatrn, "_"));
trace(variables);
// navigate with %5f:
request.data = variables.toString();
navigateToURL(request);
// navigate with underscore:
request.data = variables.toString().replace(undPatrn, "_");
navigateToURL(request);
trace(unescape(variables.toString()));

How can I pass json string into HtmlHelper's result?

I want to pass a serialized json object and returned it within custom Html Helper's result. Something like this
public static HtmlString SomeHelper(this HTMLHelper htmlHelper)
{
var MyObject = new Foo();
var oSerializer = new JavaScriptSerializer();
var str = string.Format(#"<a href""#""
onclick=""var myObject = $.parseJSON(0);
alert('my object name property '+ myObject.Name); ""> Click me</a>",
oSerializer.Serialize(MyObject));
return new HtmlString(str);
}
That thing theoretically should work, but it doesn't. It puts serialized string to markup and then everything gets messy, because of double and single quotes. I tried to apply HtmlString after serialization, I even tried to use HTmlString.ToHtmlString(). Nothing works.
In fact I probably shouldn't do that. The click event call should be used unobtrusively. I know. Then I still have to save json object somewhere in the resulting markup.
Upd: I even tried to do that:
sJson.replace("\"",""")
Not helping. Browser automatically converts "s into ". I don't know how to preserve the markup
Is html.Encode the answer?
return new HtmlString(Html.Encode(str));
I guess the only solution would be to replace all double quotes in oSerializer.Serialize(MyObject)) with some other symbol, which wouldn't conflict in html markup, and then before the parsing put double quotes back, otherwise it wouldn't be a legit json string.