I want to parse the following string (using Javascript):
color(alias(sumSeries(sys.mem.free.*),"memory (free)"),"#00AA88")
into an array of function names and arguments:
[["color", "#00AA88"],
["alias", "memory (free)"],
["sumSeries", ""]]
plus extract the innermost string
sys.mem.free.*
The string is actually the target parameter from graphite.
I don't want to write a parser myself (dealing with things like double quotes and brackets is hard to get right).
Is there a library which helps with basic parsing?
Since it's not JSON I cannot go for a JSON parser.
Related
I'm parsing a Uint8 array that is an HTML document. It contains a script tag which in turn contains JSON data that I would like to parse.
I first converted the array to text:
data = Buffer.from(str).toString('utf8')
I then searched for the script tag, and extracted the string containing the JSON:
... {\"phrase\":\"Go to \"California\"\",\"color\":\"red\",\"html\":\"<div class=\"myclass\">Ok</div>\"} ...
I then did a replace to clean it up.
data = data.replace(/\\"/g, "\"").replace(/\\/g, "").
{"phrase":"Go to "California"","color":"red","html":"<div class="myclass">Ok</div>"}
I tried to parse using JSON.parse() and got an error because the attributes contain quotes. Is there a way to process this further using a regex ? Or perhaps a library? I am working with Cheerio, so can use that if helpful.
The escape characters are necessary if you want to parse the JSON. The embedded quotes would need to be double escaped, so the extracted text isn't even valid JSON.
"{\"phrase\":\"Go to \\\"California\\\"\",\"color\":\"red\",\"html\":\"<div class=\\\"myclass\\\">Ok</div>\"}"
or, using single quotes:
'{"phrase":"Go to \\"California\\"","color":"red","html":"<div class=\\"myclass\\">Ok</div>"}'
Thanks.
After some more tinkering around, I realized that I should have encoded the data to Uint8 at the source (a Lambda function) before transmitting it for further processing. So now, I have:
Text
Encoded text to Uint8
Return from Lambda function.
Decode from Uint8 to text
Process readily as no escape characters.
Before, I was skipping step 2. And so Lambda was encoded the text however it does by default.
I am getting the following json object when I call the URL from Browser which I expect no data in it.
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
However, when I tried to call it in javascript it gives me error Parsing Json message
dspservice.callService(URL, "GET", "", function (data) {
var dataList = JSON.parse(data);
)};
This code was working before I have no idea why all of a sudden stopped working and throwing me error.
You say the server is returning the JSON (omitting the enclosing quotes):
{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}
This is invalid JSON. The quote marks in JSON surrounding strings and property names should not be preceded by a backslash. The backslash in JSON is strictly for inserting double quote marks inside a string. (It can also be used to escape other characters inside strings, but that is not relevant here.)
Correct JSON would be:
{"data":[], "SkipToken":"", "top":""}
If your server returned this, it would parse correctly.
The confusion here, and the reports by other posters that it seems like your string should work, lies in the fact that in a simple-minded test, where I type this string into the console:
var x = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
the JavaScript string literal escaping mechanism, which is entirely distinct from the use of escapes in JSON, results in a string with the value
{"data":[], "SkipToken":"", "top":""}
which of course JSON.parse can handle just fine. But Javascript string escaping applies to string literals in source code, not to things coming down from the server.
To fix the server's incorrectly-escaped JSON, you have two possibilities. One is to tell the server guys they don't need to (and must not) put backslashes before quote marks (except for quote marks inside strings). Then everything will work.
The other approach is to undo the escaping yourself before handing it off to JSON.parse. A first cut at this would be a simple regexp such as
data.replace(/\\"/g, '"')
as in
var dataList = JSON.parse(data.replace(/\\"/g, '"')
It might need additional tweaking depending on how the server guys are escaping quotes inside strings; are they sending \"\\"\", or possibly \"\\\"\"?
I cannot explain why this code that was working suddenly stopped working. My best guess is a change on the server side that started escaping the double quotes.
Since there is nothing wrong with the JSON string you gave us, the only other explanation is that the data being passed to your function is something other than what you listed.
To test this hypothesis, run the following code:
dspservice.callService(URL, "GET", "", handler(data));
function handler(data) {
var goodData = "{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}";
alert(goodData); // display the correct JSON string
var goodDataList = JSON.parse(goodData); // parse good string (should work)
alert(data); // display string in question
var dataList = JSON.parse(data); // try to parse it (should fail)
}
If the goodData JSON string can be parsed with no issues, and data appears to be incorrectly-formatted, then you have the answer to your question.
Place a breakpoint on the first line of the handler function, where goodData is defined. Then step through the code. From what you told me in your comments, it is still crashing during a JSON parse, but I'm willing to wager that it is failing on the second parse and not the first.
Did you mean that your JSON is like this?
"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"
Then data in your callback would be like this:
'"{\"data\":[], \"SkipToken\":\"\", \"top\":\"\"}"'
Because data is the fetched text content string.
You don't have to add extra quotes in your JSON:
{"data":[], "SkipToken":"", "top":""}
here is the output of a php json_encode() call:
//start
//docStructure version 1.0.alpha compiled September 16th, 2014 at 9:18PM
var docStructure={"updateTime":"2014-09-16 21:18:19","listeners":[{"name":"eFaxListener","active":"0","url":"?action=faxvcheckinboundfax"}],"sections":{"defaultLayout":{"header":[]}},"editors":{"sideeditor":{"state":"closed","width":"0","context":""}}}//end
note the keys all have double quotes around them.
I would prefer to have the keys NOT have double quotes for easier reading. Is there any difference? I would prefer to identify as
alert(docStructure.editors.siteeditor.state);
vs.
alert(docStructure['editors']['siteeditor']['state'])
Or can I stil use these interchangeably with the keys as strings?
Thanks, this is building my understanding of javascript's thinking..
The JSON format requires the keys to be double quoted, once parsed by javascript its just a normal object, so you can access them both ways, assuming your keys are valid object keys(not starting with a number or a special character).
You are looking for jQuery.parseJSON( json )
Description:
Takes a well-formed JSON string and returns the resulting JavaScript object.
I'm calling a service that returns UTF-16 json data.
My question is if the JSON object has UTF-16 strings as property names is there a simple way to reference these properties?
For example, here is how the response data looks like after calling JSON.stringify on it:
"{"C\u0000o\u0000n\u0000t\u0000e\u0000n\u0000t\u0000s\u0000":{ ...
In my code I'd like to do something like data['Contents']. Is there a simple way around this that avoids either hardcoding the strings with unicode escape sequences?
Update: changed to indicate strings are UTF-16.
Here's an example (Visual C++) of the call to generate the JSON output:
wchar_t* str = _T("Contents");
yajl_gen_string(g, (unsigned char*)str, wcslen(str) * sizeof(TCHAR));
In my web application, why do JSON.stringify serialize my Activity's Trackpoints array as a string? Notice in the JSON representation on top that the trackpoints array is enclosed in quotes, rendering it as a string. The javascript object representation in the bottom shows clearly that trackpoints is an array.
When this serialized activity is passed as JSON in a POST to my Sinatra back-end, Ruby parses its trackpoints as a string instead of an array of Trackpoint objects. The end result is a 500 server error, which is not what I expect.
Precision for people unable to see the included image: "The trackpoints array is a property of a complex object. JSON.stringify encloses it in quotes while doing its job. When Ruby parses the whole serialized object, it interprets my array as a string instead of an array. That's why I want to avoid those quotes."