Building json object with nested arrays in vb.net - json

I have a json structure and I need to build it dynamically using .net the example provided is:
'{"payload":{"message" : <message>, "badge" : <badge>}[, "filter" : {"deviceID" : <deviceID criteria>,"<param1>" : <criteria>, ...}][, "schedule": {"scheduledTime": > <scheduled_time>, "useTimeZone": <use_time_zone>}]}'
So far I have been able to get only the first part of the json completed using:
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Using writer As JsonWriter = New JsonTextWriter(sw)
writer.Formatting = Formatting.Indented
writer.WriteStartObject()
writer.WritePropertyName("payload")
writer.WriteStartObject()
writer.WritePropertyName("message")
writer.WriteValue("Hello World!")
writer.WritePropertyName("badge")
writer.WriteValue(7)
writer.WriteEnd()
End Using
this gives me:
{
"payload": {
"message": "Hello World!",
"badge": 7
}
And then if I try to introduce the array using writer.WriteStartArray() I get errors, how do I do this correctly?
I have now got to the bottom of the correct way to construct the json at least in jquery! The syntax is;
var T = 'This is a Test!';
var D = '1';
return {"message": T , "badge": D };

As you can see, JSon output from your current code missing single closing curly bracket. I'm not sure, but that could be the cause of error when you add writer.WriteStartArray(). Try to fix missing closing curly bracket by calling WriteEndObject :
writer.WriteValue("Hello World!")
writer.WritePropertyName("badge")
writer.WriteValue(7)
writer.WriteEndObject()
writer.WriteEndObject()
End Using
UPDATE :
I think square bracket in the specification doesn't mean an array. I somehow believe it means that part inside the square bracket is optional property.
[, "filter" : {"deviceID..."}]
notice a comma at the beginning of square bracket content, it indicates that filter is another property you can append after two mandatory properties message and badge.

Related

Unnable to read json response in reactjs

I need to replace a value in the response ,
My Json format :
{"Message":"","IsSuccessful":true,"sample2.0com":["data1","data2"],"sample1.0com":["data3","data4","data5","data6"]}}
When I am trying to read the above response , I am facing issue
let sample2 = response.data.Result.sample2.0com;
Please give me a solution to read sample2.0com components from the response
Keys that are not valid JavaScript variable names (start with one of a-zA-Z_$ and contain only a-zA-Z0-9_$) must be accessed as strings inside square brackets ([]).
For example: obj.camelCase is OK, but obj.this key contains spaces is not OK - it would have to be obj['this key contains spaces'].
JSON objects are surrounded by curly braces {}.
You can access the object values by using dot . notation:
myObj = { "name":"John", "age":30, "car":null };
x = myObj.name;
You can also access the object values by using bracket ([]) notation:
myObj = { "name":"John", "age":30, "car":null };
x = myObj["name"];
Similarly you can use as like above
responseData = {"Message":"","IsSuccessful":true,"sample2.0com":["data1","data2"],"sample1.0com":["data3","data4","data5","data6"]}}
let sample2 = responseData["sample2.0com"];
This will fix yours
Is because of your . in the sample2.0com.. you have to use the [] to call the property, so use response.data.Result['sample2.0com'], but I am not sure what is the "Result" object ... maybe you should use response.data['sample2.0com']

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

Create JSON from a String

I am trying to create a json from this String
var json = { data: [v1,v2], con: [begin: "test1", end: "test2"] };
What is wrong with the String? I get an error SyntaxError: Unexpected token :It is not possible to set a key for the value test1 and test2?
In JavaScript:
An object literal, which uses the {} syntax, consists of a collection of property: value pairs.
An array literal, which uses the [] syntax, consists of a collection of values.
[begin: "test1", end: "test2"]
You have used the array syntax here, but have tried to put property: value pairs inside it.
This causes your error, the : isn't expected.
You probably want to use the {} there. Alternatively, you want to remove begin: and end:.
This has nothing to do with JSON or strings. It is simply JavaScript.
You are instantiating a javascript Object.
const toto = {};
is the same as
const toto = new Object();
This is a String javascript object, which hold a string representation of a json.
const toto = "{ \"key\": \"value\" }";
Try
var json = { data: ["v1","v2"], con: [{begin: "test1"}, {end: "test2"}] };
It looks like you might have a blocking error.

cordova readAsText returns json string that can't be parsed to JSON object

I read my json file using http and cordova file readAsText functions.
http request returns an object which is ok.
cordova file readAsText function return 'string' which contain extra "r\n\" symbols. This make it impossible to use JSON.parse(evt.target.result)
function readJson(absPath, success, failed){
window.resolveLocalFileSystemURL(absPath, function (entry) {
entry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
success(evt.target.result);
};
reader.readAsText(file);
}, failed);
}, failed);
}
readJson(cordova.file.dataDirectory + 'my.json', function(res){
console.log(JSON.parse(res)); //here I've got an parsing error due to presence of r\n\ symbols
}, failed );
How to read JSON files using cordova?
UPDATE:
funny thing that the following works:
a = '{\r\n"a":"1",\r\n"b":"2"\r\n}';
b = JSON.parse(a);
so the problem not only with \r\n... there is something else that is added by cordova readAsText
UPDATE2
as a workaround I use now var object = eval("(" + res + ")")
Still search for a common way to load json objects...
No one has answered this and I just had to solve it for my project, so I will post my solution.
The readAsText method outputs a string, so you CAN actually run a replace on it, but what you need to do is use a RegExp to find the newline character. here's my solution:
var sanitizerRegex = new RegExp(String.fromCharCode(10), 'g');
var sanitizedData = JSON.parse(result.replace(sanitizerRegex, ''));
I've used the String method fromCharCode to get the specific newline character and the "g" flag to match all instances in the entire string. The problem with your string solution is that you can't do a string replace using the characters for backslash and "n" because the issue is the actual new line character, which is merely represented as "\n".
I do not know the reason JSON.parse can't handle the newline character, or why the file plugin introduces this problem, but this solution seems to work for me.
Also, NEVER use eval like this if you can avoid it, especially on input from a source like a JSON file. Even in a cordova app, using eval is potentially very unsafe.
I found out the solution after debug deeply. readAsText function returned text has one more letter at the first position of text.
Example:
{"name":"John"} => ?{"name":"John"} (?: API didn't return ?, just one string)
I confirmed this with length of result, so we need to use substr(1) before parse JSON.
fileContent = fileContent.substr(1);
var jData = jQuery.parseJSON(fileContent);

JSON.parse: expected property name or '}'

Data contains (/"/):
{"test":"101","mr":"103","bishop":"102"}
script:
console.log($.parseJSON(result));
I'm getting error,
JSON.parse: expected property name or '}'.
Had same issue when used single quotes in JSON file, changed to double quotes for all string properties/values and it's working OK now.
Change:
JSON.parse("{'wrongQuotes': 5}")
To:
JSON.parse('{"rightQuotes": 5}')
If you're receiving the JSON with the encoded ", you'll have to replace each instance of " with a true " before doing JSON.parse. Something like:
myJSONstring.replace(/"/ig,'"');
My case was even simpler.
Having confused JSON with plain JS, I didn't put the object keys in double quotes.
❌:
{
title: "Hello World!"
}
✅:
{
"title": "Hello World!"
}
The irony is, Postman even highlighted this to me, but I ignored. Sleep is the answer.
For anyone who is using laravel blade and declaring a JS variable in a view.
You need to use:
var json = JSON.parse('{!! $json !!}');
Otherwise you will get this error due to the quotes being parsed as "
Change
{"test":"101","mr":"103","bishop":"102"}
To
'{"test":"101","mr":"103","bishop":"102"}'
if this is coming from the server (PHP)
i.e <?php $php_var = ["test" => "101", "mr" => "103", "bishop" => "102"]?>
then on Javascript end
var javascript_var = $.parseJSON('<?= json_encode($php_var) ?>');
/* suppose your json are single quote, it's necessary replace it single quote before, a simple example*/
let ojson = "{'name':'peterson'}";
ojson = ojson.replace(/'/g, '"');
ojson = JSON.parse(ojson);
console.log(ojson['name'])
for example, if u get something like this
{ "location": "{'lat': 4.6351144, 'lng': -74.12011199999999}" }
from your server, or recently get a bad converted format.
first,get your string
myItemString = "{'lat': 4.6351144, 'lng': -74.12011199999999}"
and change the keys using replace, and later json.parse,
'key' to ---> "key"
const key1 = myItemString.replace("'lat'",'"lat"')
const key12 = key1.replace("'lng'", '"lng"');
const obj = JSON.parse(key12)
console.log(obj)
You can try using stringifying before parsing:
JSON.parse(JSON.stringify(result))