JSON for newbs - for Adobe Brackets functionality - json

I am completely unfamiliar with JSON. I don't use it on a regular basis so I'm just looking for a quick fix, but as a programmer I'd love some basic understanding also.
I'm using Brackets to edit some content for work, and auto-complete is driving me CRAZY. I hate you auto-complete, I hate you so much. I found a snippet of code at https://github.com/talmand/Brackets-Disable-AutoClose-Tags which is supposed to negate auto-complete when opening a new tag. It does not totally shut off auto-complete - it still tries to complete your closing tag once begun. Intended to be useful but I find it intensely irritating.
I inserted the code into the Preferences File, and in the statement, it seems pretty obvious that all I should need to do is change whenClosing to false, but when I do it, then close and reopen the program so it'll take effect, it tells me that my Preferences File contains invalid JSON. All I changed was the value true to false for whenClosing. I used JSONlint to try and see what's wrong, but JSON is not a familiar language for me. Code is included below.
What am I doing wrong?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
This is the unaltered code that I copied into the file:
"closeTags": { "whenOpening": false, "whenClosing": true, "indentTags": [] }
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
And this is the total block that my Preferences File contains, with my edit:
{
"closeBrackets": false,
"debug.showErrorsInStatusBar": true
}
"closeTags": { "whenOpening": false, "whenClosing": false, "indentTags": [] }
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
And this is what JSONlint said:
Parse error on line 4:
...InStatusBar": true}"closeTags": { "
----------------------^
Expecting 'EOF', '}', ',', ']'
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#Shaunak that makes sense! I added the comma though, and got this:

You need a comma after closing bracket.
{
"closeBrackets": false,
"debug.showErrorsInStatusBar": true
}, <<<<<<<<< ----- You need a comma here :)
"closeTags": { "whenOpening": false, "whenClosing": false, "indentTags": [] }
JOSN object properties need to be saperated by a comma. Which is what the JSLint is telling you in that error.
UPDATE
Okay I suspected this, but thought you had only pasted partial code initially. Your preferences.json should actually look like this:
{
"closeBrackets": false,
"debug.showErrorsInStatusBar": true,
"closeTags": { "whenOpening": false, "whenClosing": false, "indentTags":[] }
}
So your problem was that, all preferences need to go in the main {} object. Without that main wrapping {} the JSON is invalid.
In future I recommend https://www.jsoneditoronline.org/ to validate and inspect your JSON strings.

Related

Why can't I read JSON files in certain parts of my project?

I am working on an angular project and want to edit a JSON value based on the key of the key value pair on the click of a button to match user input from a textfield. I am working on this project with others who did the heavy lifting so a lot of it is just learning the structure. I try to use
const fs = require("fs");
then
fs.readFileSync
to get into the file.
This is what other users have done on other parts of the projects but when I do it I get an error saying TypeError:
fs.readFileSync is not a function, or it doesn't recognize fs at all.
I have tried adding things like
"browser": {
"fs": false,
"path": false,
"os": false,
"crypto": false,
"stream": false,
"http": false,
"tls": false,
"zlib": false,
"https": false,
"net": false
}
to my package.json files, both in my module and in the root project, but nothing seems to be working.
Fs works in some parts of the project that others have worked on but I can't get it to work on mine and I can't figure out how to edit the JSON values based on the user input.
I know this is a vague question but does anyone have any ideas or follow up questions I could answer that might lead to something?

how can I access this data on data.d.results

I am trying to access the Title data found in the image below via rest. Nothing allows me to get it. I have tried:
data.d.results[0].Title
Perhaps it's an issue with backlash before double quotes. Tested with:
let data = {d: { results: [ { Title: "\"hello\"", } ] }}
console.log(data.d.results[0].Title);
Worked fine. Can't provide answer without more context

FullCalendar json feed error

I am trying to fill my FullCalendar with events using json. But I get an error when trying to load such events. Since I am new to all of this I was trying to load just a single event and I am not even getting the info from a database for now.
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
theme:true,
allDaySlot: false,
allDayText: false,
minTime: 7,
maxTime: 19,
events: {
url: 'JornadasDeportivas.php',
type: 'POST',
data: {
opcion: 'eventos',
},
error: function() {
alert('Error al cargar los eventos');
}
}
});
My php code is just calling this method
function json(){
echo '
[
{
"title" : "event1",
"allDay" : false,
"start" : "2011-09-09 12:30:00",
"end" : "2011-09-09 15:30:00"
}
]
';
}
and the output is
[ { "title" : "event1", "allDay" : false, "start" : "2011-09-09 12:30:00", "end" : "2011-09-09 15:30:00" } ]
and I always get the error alert. I don't know what I'm doing wrong.Pleeeeaseee help!!! :( Thanks in advance!
as it was said there should be no comma after " opcion: 'eventos' ", last objects attribute (and that also goes for fields in array) should not be followed comma. Most of browsers dont really care about it (for me Chrome/FF are just ignoring it), but IE (at least version 7 I use for some checks) shows an error.
Another problem you can be facing is that your headers are not set correctly. For proper json reading some browser require response with strict "application/json" header, but for IE7 (dont have 8+ so cant say for those for sure) you need to return "text/plain".
There also could be some problem with timeFormat you use, at least in documentation in timeFormat section they show an event time in "2010-01-01T14:30:00" format, so try putting "T" instead of space.
In your case, I would build an event object as normaly php array, set proper header and display it with json_encode function.
I'm not sure but is it the comma after opcion: 'eventos',

Ajax JSON Parse Error

I find this kinda strange. it works on older versions of iQuery (ie 1.2.x to 1.3). However, i am getting a parserror when using jQuery 1.4.x
Any help will be appreciated. Thank you.
This is what i get from XMLHttpRequest.responseText
({count: 5, success: true, error: '', cache: false, data: [{column: ['Mike','Mike','Steve','Steve','Steve']}]})
Jquery 1.4 updated their JSON parser, so that it no longer accepts invalid JSON that it did before. Your server is outputting invalid JSON that was previously tolerated, but no longer is. This change was mentioned (briefly) in the release notes and documentation, and there's been lots of discussion about it if you google "jquery 1.4 JSON"
But to sum up: the keys in JSON, to be valid, must have quotes around them, the string can't be surrounded by those parentheses, and nothing can use single quotes as delimiters, so your JSON would need to be:
{"count": 5, "success": true, "error": "", "cache": false, "data": [{"column": ["Mike","Mike","Steve","Steve","Steve"]}]}
or, more readably:
{
"count": 5,
"success": true,
"error": "",
"cache": false,
"data": [
{
"column": [
"Mike",
"Mike",
"Steve",
"Steve",
"Steve"
]
}
]
}
The specs are very nicely and clearly spelled out at http://www.json.org/ with pictures and diagrams. You can also check your JSON at JSONLint - the JSON above checks out there just fine, but your original JSON raises all kinds of errors.
So as to what you need to do: if you have the ability to change what your server sends out, do that - make it output valid JSON. Please. Only if you are unable to change the server's behavior, you'll have to use a workaround from one of the posts linked above, or use some other JSON library.
General principle: in all cases, doing it the Right Way™ is preferable - fixing the server's output (even if that's filing a bug on an external server/API) is the long-term solution, but may not be immediately practical. So hackish workarounds are sometimes necessary, but not optimal.

Proper way to deal with variations in JSON serialization

I have a web service that uses Python's SimpleJSON to serialize JSON, and a javascript/ client that uses Google's Visualization API. When I try to read in the JSON response using Google Data Table's Query method, I am getting a "invalid label" error.
I noticed that Google spreadsheet outputs JSON without quotes around the object keys. I tried reading in JSON without the quotes and that works. I was wondering what was the best way to get SimpleJSON output to be read into Google datable using
query = new google.visualization.Query("http://www.myuri.com/api/").
I could use a regex to remove the quotes, but that seems sloppy. The javascript JSON parsing libraries I've tried won't read in JSON syntax without quotes around the object keys.
Here's some good background reading re: quotes around object keys:
http://simonwillison.net/2006/Oct/11/json/.
Are you certain the Google API is expecting JSON? In my experience Google's APIs tend not to be massively broken in a manner you're describing -- it could be that they're actually expecting a different format that merely resembles JSON.
Further poking around reveals instructions for retrieving data in the format Google expects:
For example, to get the dataSourceUrl
from a Google Spreadsheet, do the
following:
In your spreadsheet, select the range of cells.
Select 'Insert' and then 'Gadget' from the menu.
Open the gadget's menu by clicking on the top-right selector.
Select menu option 'Get data source URL'.
I did this and opened the URL in my browser. The data it was returning was certainly not JSON:
google.visualization.Query.setResponse(
{requestId:'0',status:'ok',signature:'1464883469881501252',
table:{cols: [{id:'A',label:'',type:'t',pattern:''},
{id:'B',label:'',type:'t',pattern:''}],
rows: [[{v:'a'},{v:'h'}],[{v:'b'},{v:'i'}],[{v:'c'},{v:'j'}],[{v:'d'},{v:'k'}],[{v:'e'},{v:'l'}],[{v:'f'},{v:'m'}],[{v:'g'},{v:'n'}]]}});
It looks like the result is intended to be directly executed by the browser. Try modifying your code to do something like this:
# old
return simplejson.dumps ({"requestId": 1, "status": "ok", ...})
# new
json = simplejson.dumps ({"requestId": 1, "status": "ok", ...})
return "google.visualization.Query.setResponse(%r);" % json
The "invalid label" error is usually due to a blind eval() on the JSON string, resulting in property names being mistaken as labels (because they have the same syntax -- "foo:").
eval("{ foo: 42, bar: 43 }"); // Results in invalid label
The quick remedy is to make sure your JSON string has parenthesis enclosing the curly braces:
eval("({ foo: 42, bar: 43 })"); // Works
Try enclosing your JSON string in parenthesis to see if the "invalid label" error goes away.
As it turns out :mod:json would also choke at strings in single quotes. This will sort things out though:
Parse JavaScript object as JSON in python:
solution:
>>> from re import sub
>>> import json
>>> js = "{ a: 'a' }"
>>> json.loads(sub("'", '"', sub('\s(\w+):', r' "\1":', js)))
{u'a': u'a'}
Edit: (edge cases reviewed)
So it was brought up that the suggested solution would not cope with all cases and specifically with something like
e.g. {foo: "a sentence: right here!"} will get changed to {"foo": "a "sentence": right here!"}
– Jason S Apr 12 at 18:03
To resolve that we simply need to ensure that we are in fact working with a key and not simply a colon in a string so we do a little look behind magic to hint at a comma(,) or a curly brace({) presence to ensure we have it proper, like so:
colon in string:
>>> js = "{foo: 'a sentence: right here!'}"
>>> json.loads(sub("'", '"', sub('(?<={|,)\s*(\w+):', r' "\1":', js)))
{u'foo': u'a sentence: right here!'}
Which of course is the same as doing:
>>> js = "{foo: 'a sentence: right here!'}"
>>> json.loads(sub('(?<={|,)\s*(\w+):', r' "\1":', js).replace("'",'"'))
{u'foo': u'a sentence: right here!'}
But then I pointed out that this is not the only flaw because what about quotes:
If we are also concerned about escaped quotes we will have to be slightly more specific as to what constitutes a string. The first quote will follow either a curly brace({) a space(\s) or a colon(:) while the last matching quote will come before either a comma(,) or a closing curly brace(}) then we can consider everything in between as part of the same string, like so:
additional quotes in string:
>>> js = "{foo: 'a sentence: it\'s right here!'}"
>>> json.loads(
... sub("(?<=\s|{|:)'(.*?)'(?=,|})",
... r'"\1"',
... sub('(?<={|,)\s*(\w+):', r' "\1":', js))
... )
{u'foo': u"a sentence: it's right here!"}
Watch this space as more edge cases are revealed and solved. Can you spot another?
Or for something more complex perhaps, a real world example as returned by npm view:
From:
{ name: 'chuck',
description: 'Chuck Norris joke dispenser.',
'dist-tags': { latest: '0.0.3' },
versions: '0.0.3',
maintainers: 'qard ',
time: { '0.0.3': '2011-08-19T22:00:54.744Z' },
author: 'Stephen Belanger ',
repository:
{ type: 'git',
url: 'git://github.com/qard/chuck.git' },
version: '0.0.3',
dependencies: { 'coffee-script': '>= 1.1.1' },
keywords:
[ 'chuck',
'norris',
'jokes',
'funny',
'fun' ],
bin: { chuck: './bin/chuck' },
main: 'index',
engines: { node: '>= 0.4.1 < 0.5.0' },
devDependencies: {},
dist:
{ shasum: '3af700056794400218f99b7da1170a4343f355ec',
tarball: 'http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz' },
scripts: {},
directories: {},
optionalDependencies: {} }
To:
{u'author': u'Stephen Belanger ',
u'bin': {u'chuck': u'./bin/chuck'},
u'dependencies': {u'coffee-script': u'>= 1.1.1'},
u'description': u'Chuck Norris joke dispenser.',
u'devDependencies': {},
u'directories': {},
u'dist': {u'shasum': u'3af700056794400218f99b7da1170a4343f355ec',
u'tarball': u'http://registry.npmjs.org/chuck/-/chuck-0.0.3.tgz'},
u'dist-tags': {u'latest': u'0.0.3'},
u'engines': {u'node': u'>= 0.4.1 < 0.5.0'},
u'keywords': [u'chuck', u'norris', u'jokes', u'funny', u'fun'],
u'main': u'index',
u'maintainers': u'qard ',
u'name': u'chuck',
u'optionalDependencies': {},
u'repository': {u'type': u'git', u'url': u'git://github.com/qard/chuck.git'},
u'scripts': {},
u'time': {u'0.0.3': u'2011-08-19T22:00:54.744Z'},
u'version': u'0.0.3',
u'versions': u'0.0.3'}
Works for me =)
nJoy!