What is this file format called - json

I need to parse a file which is in the following format:
"General"
{
"Description" = "Some Text"
"Version" = "4"
"ProjType" = "1"
}
"Configurations"
{
"Mice"
{
"BuildOutputs" = "BuildProject"
"OutputFile" = "output.txt"
}
"Men"
{
"BuildOutputs" = "BuildProject"
"ChangedSinceLastBuilt" = "True"
}
}
Does anyone have any idea what file format this is? If it's well known then there could be already made libraries to help parse it. It appears to be similar to JSON but instead of colons it uses equals sign and instead of commas it forcefully uses a new line.

You could simply read in the entire file and then convert = to : and each line break with , - then you could parse it with an existing json library. Perhaps you would have to insert a ; at the end of the data.

Related

How to properly build and append a json file from variables

I'm practising programming an application that takes user input and then outputs it to a json file.
I found a how to that explains how to do it. For the sake of length, I'm leaving out the input code and just including the json builder.
ASSIGN
uComp = "testCompany"
uEmail = "testEmail"
uName = "testName"
uAdd = "Additional"
.
DEFINE VARIABLE myObj AS JsonObject NO-UNDO.
DEFINE VARIABLE myData AS JsonObject NO-UNDO.
DEFINE VARIABLE dataParams AS JsonObject NO-UNDO.
DEFINE VARIABLE lResult AS LONGCHAR NO-UNDO
VIEW-AS EDITOR LARGE SIZE 60 BY 16.
DEFINE VARIABLE lJArray AS JsonArray NO-UNDO.
DEFINE VARIABLE lAnotherArray AS JsonArray NO-UNDO.
OUTPUT TO "output path.json".
myObj = NEW JsonObject().
dataParams = NEW JsonObject().
myObj:Add("id", "01").
dataParams:Add("Company_name", uComp).
dataParams:Add("uEmail", uEmail).
dataParams:add("uName", uName).
dataParams:add("AddInfo", uAdd).
lJArray = NEW JsonArray().
lJArray:Add(dataParams).
myObj:Add("data", lJArray).
myObj:Write(lResult, TRUE).
DISPLAY lResult.
That part works fine, but my output is like so:
lResult-----------------------------------------------------
{
"id": "01",
"data": [
{
"Company_name": "testCompany",
"uEmail": "testEmail",
"uName": "testName",
"AddInfo": "Additional"
}
]
}
how do I prevent the
lResult-----------
from being added to the file.
Secondly, I want to add additional information to the file when the code runs again so that the output will become.
{
"id": "01",
"data": [
{
"Company_name": "testCompany",
"uEmail": "testEmail",
"uName": "testName",
"AddInfo": "Additional"
},
{
"Company_name": "testCompany",
"uEmail": "testEmail",
"uName": "testName",
"AddInfo": "Additional"
}
]
}
What is the correct way to target a point in the file and add additional objects?
I though it might be something along the lines of an
append
property.
I would leave the complete JSON I/O to the JSON parser in the language. So instead of the append, I'd read in the file into a JSON object and add the additional objects/properties in memory and write back to a file.
Just an output with append won't produce value JSON. This should work:
FILE-INFORMATION:FILE-NAME = "myfile.json" .
IF FILE-INFORMATION:FULL-PATHNAME > "":U THEN DO:
myObj = CAST ((NEW ObjectModelParser()):ParseFile(FILE-INFORMATION:FULL-PATHNAME),
JsonObject) .
lJArray = myObj:GetJsonArray("data") .
END.
ELSE DO:
myObj = NEW JsonObject().
myObj:Add("id", "01").
lJArray = NEW JsonArray().
myObj:Add("data", lJArray).
END.
dataParams = NEW JsonObject().
dataParams:Add("Company_name", uComp).
dataParams:Add("uEmail", uEmail).
dataParams:add("uName", uName).
dataParams:add("AddInfo", uAdd).
lJArray:Add(dataParams).
myObj:WriteFile("myfile.json", TRUE).
how do I prevent the
lResult-----------
from being added to the file.
I suspect it's because the variable has a VIEW-AS phrase on the definition. But using the JsonObject as an object and calling the WriteFile method is the (far) better approach.

Building json object with nested arrays in vb.net

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.

JSON parsing: Unexpected Token error

Im trying to parse a string to JSON and I'm getting an unexpected token error.
I am checking validity using http://json.parser.online.fr/ which comes up with no parse errors, but still says the eval fails due to an unexpected token. If you paste the JSON from below in to that website you can see that it finds an error, but doesn't specify what token is causing it.
Heres what I'm trying to parse.
{
"Polish": {
"Rent": [
{
"english": "a",
"audioUrl": "b",
"alternate": "c"
},
{
"english": "d",
"audioUrl": "e",
"alternate": "f"
}
]
}
}
Am I missing something obvious?
EDIT
There is an unprintable character inbetween the : and [ after the "Rent" key.
I am doing some replace() calls on the string prior to the parse attempt which are likely creating the problem.
prior to the parse that particular line is
"Rent":"[
I want to remove the doublequote between the : and [ sybmols.
So I am using:
var reg = new RegExp('":"', 'g');
var newStr = originalStr.replace(reg, '":');
I don't know why the above is causing the unprintable character though.
EDIT2
I did a quick check removing the Above replace() call pasted it into the validator, manually removed the doublequotes I was using replace() on, and the unreadable characters are still there. So the error is present in the original string. So more code :|
The string is being returned from an ajax call to a php script residing on a server. The PHP script is reading a directory on the server and populating nested associative array to produce the string which is sent back to the JS side, which edits and parses it (shown above).
Within the directories are JSON files, which I'm inserting the contents of into this nested array structure to complete the JSON hierarchy.
The unreadable characters were
ef bb bf
Which I googled and found to be the Byte Order Mark of the string representing the file contents.
So heres the PHP Code which reads the directories and JSON files creating a nested array structure to be JSON_encode()d and sent back to the JS
if ($langHandle = opendir($langDir)) {
while (false !== ($langEntry = readdir($langHandle))) {
$currentLangDir = $langDir . "/" . $langEntry;
if (is_dir($currentLangDir) && $langEntry != '.' && $langEntry != '..') {
$currentLang = array();
if ($currentLangHandle = opendir($currentLangDir)) {
while (false !== ($catEntry = readdir($currentLangHandle))) {
$currentCatFile = $currentLangDir . "/" . $catEntry;
if(is_file($currentCatFile) && $catEntry != '.' && $catEntry != '..') {
$currentCat = file_get_contents($currentCatFile);
$currentLang[removeFileExtension($catEntry)] = $currentCat;
}
}
}
$langArray[$langEntry] = $currentLang;
}
}
What can I do to fix these unwanted characters, a quick search on removing the BOM chars suggests it is a bad thing to do.
You probably have a non printable character that is not showing up in what you pasted in your question. I copied and pasted your text into the online parser at the link you provided and it parses cleanly.
Try copying and pasting your original text into this online hex dump website, and compare to what you get when you copy and paste from your SO question above... if they differ then you'll have a clue as to where the bogus character is.
Here's a screenshot of the output I got, which parses cleanly.
Bro, I was having a similar problem, check your file encoding (UTF-8) and (UTF-8 WITHOUT BOM) can make a difference.

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

JSON String formed improperly using Jayrock in .NET

I am trying to return a JSON object from an aspx page using Jayrock.JSON.
My code for writing it out is this:
using (JsonTextWriter writer = new JsonTextWriter(Response.Output))
{
writer.WriteStartObject();
for (int i = 0; i < rdr.FieldCount; i++)
{
writer.WriteMember(rdr.GetName(i).ToString());
writer.WriteString(rdr[i].ToString());
}
writer.WriteEndObject();
}
This is inside of an rdr.Read() loop.
The outputted JSON looks like this: (though I added the line breaks manually)
{
"BugID":"1087",
"AddedBy":"",
"BugDate":"5/2/2010 9:45:34 AM",
"BugTitle":"/admin/ajax_thirdpartylog.asp",
"Classify":""
,"ErrPage":"/admin/ajax_thirdpartylog.asp",
"StoreID":"71",
"UserID":"15438",
"ErrDesc":"Type mismatch: 'formatnumber'",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\ncalmonth : 8\r\ncalmonth2 : 8\r\nfromdate : 8/1/2009\r\ncalyear : 2009\r\ntodate : 8/31/2009\r\ncalyear2 : 2009\r\nr : 978402\r\nthirdtype : 1\r\nButton : Generate Third Party Log\r\n\r\n*** Query String Variables ***\r\n\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"74",
"DateFixed":"",
"Counter":"16",
"AssignTo":""
}
{
"BugID":"1086",
"AddedBy":"",
"BugDate":"5/1/2010 11:58:54 PM",
"BugTitle":"/admin/Charts/monthsales_s.asp",
"Classify":"",
"ErrPage":"/admin/Charts/monthsales_s.asp",
"StoreID":"402",
"UserID":"141928",
"ErrDesc":"Script timed out",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\n\r\n*** Query String Variables ***\r\n\r\nmonth1 : 9/1/2009\r\nr : 75333803\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"0",
"DateFixed":"",
"Counter":"",
"AssignTo":""
}
I'm not really sure what I'm doing wrong, but on my page reading this JSON, when I try to do .evalJSON (using prototypejs) I get errors saying that the JSON is malformed.
Can anyone advise me what to change?
This:
"AssignTo":""
}
{
is the invalid JSON. You can a string to see if it's valid JSON at JSON Lint. I'm not sure what this should be like, but an empty object would be like this (don't need "", brackets reversed, missing comma):
"AssignTo":
{
},
The problem is that you are writing multiple JSON objects whereas what you are probably trying to do is produce a JSON array of JSON objects. Given your code snippet, I'm assuming rdr holds some IDataReader implementation like SqlDataReader. If that's true then you need to modify your code to start and end a JSON array around the outer read loop, as follows:
using (JsonTextWriter writer = new JsonTextWriter(Response.Output))
{
writer.WriteStartArray();
while (rdr.Read())
{
writer.WriteStartObject();
for (int i = 0; i < rdr.FieldCount; i++)
{
writer.WriteMember(rdr.GetName(i).ToString());
writer.WriteString(rdr[i].ToString());
}
writer.WriteEndObject();
}
writer.WriteEndArray();
}
Jayrock will automatically delimit each JSON object value with a comma (,) when inside a JSON array so now the output should resemble the following and valid JSON:
[
{
"BugID":"1087",
"AddedBy":"",
"BugDate":"5/2/2010 9:45:34 AM",
"BugTitle":"/admin/ajax_thirdpartylog.asp",
"Classify":""
,"ErrPage":"/admin/ajax_thirdpartylog.asp",
"StoreID":"71",
"UserID":"15438",
"ErrDesc":"Type mismatch: 'formatnumber'",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\ncalmonth : 8\r\ncalmonth2 : 8\r\nfromdate : 8/1/2009\r\ncalyear : 2009\r\ntodate : 8/31/2009\r\ncalyear2 : 2009\r\nr : 978402\r\nthirdtype : 1\r\nButton : Generate Third Party Log\r\n\r\n*** Query String Variables ***\r\n\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"74",
"DateFixed":"",
"Counter":"16",
"AssignTo":""
},
{
"BugID":"1086",
"AddedBy":"",
"BugDate":"5/1/2010 11:58:54 PM",
"BugTitle":"/admin/Charts/monthsales_s.asp",
"Classify":"",
"ErrPage":"/admin/Charts/monthsales_s.asp",
"StoreID":"402",
"UserID":"141928",
"ErrDesc":"Script timed out",
"ErrDump":"*** VARIABLES DUMP ***\r\n\r\n*** Form Variables ***\r\n\r\n\r\n*** Query String Variables ***\r\n\r\nmonth1 : 9/1/2009\r\nr : 75333803\r\n\r\n\r\n*** REPORT END ***\r\n",
"ErrLine":"0",
"DateFixed":"",
"Counter":"",
"AssignTo":""
}
]