How to indent JSON data inside of TextMate, Emacs, BBEdit, or Sublime Text 2? - json

[Update: 8 hours after this question was posted, the author of JSON bundle was notified of the issue and he fixed it.]
I have the following JSON data in a file application.json, shown at the end of this post, and I have used TextMate with the JSON bundle, Emacs, BBEdit, and Sublime Text 2 to properly indent it, but all seemed like they couldn't.
Both TextMate and Sublime Text 2 insisted that the first { should not be indented, and the first major issue was for the closing brace for "child": {. Both TextMate and Sublime Text 2 refused to align the } under the left side of "child": {. Emacs kept on indenting further and further for each line, and BBEdit didn't seem to have an re-indent function at all (could this be?).
Is there a way to properly indent the file, or are TextMate and Sublime Text 2 both doing the right thing for the JSON data?
[
{
"settings": [ "master" ],
"appPort": "8666",
"specs": {
"frame" : {
"type" : "HTMLFrameMojit",
"config": {
"deploy": true,
"child": {
"type" : "HelloWorldMojit"
},
"assets": {
"top": {
"css": [
"/static/HelloWorldMojit/assets/index.css"
]
}
}
}
}
}
},
{
"settings": [ "environment:development" ],
"staticHandling": {
"forceUpdate": true
}
}
]

EDIT: For BBEdit use siegel's suggestion of Text > Reformat Document
Original Reply:
I found a solution for BBEdit that is easy and works well.
Put the following script in
~/Library/Containers/BBEdit/Data/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh (on MacOS 11 Big Sur, or above)
For MacOS 10.15 Catalina and below, use this location: ~/Library/Application Support/BBEdit/Text Filters/FormatJSON.sh
#!/bin/bash
python -m json.tool
Open a JSON file in BBEdit. There is no need to restart BBEdit because BBEdit rocks!
Select Text > Apply Text Filter > FormatJSON
I tested this with a JSON file that had 3,612,683 characters on a single line. BBEdit opened this file and reformatted without showing a "Spinning Beachball of Death" busy-wait mouse cursor.

Solution 1: Using Python
This answer is similar to this answer, except I am using python file to do the JSON format.
Exit bbedit application if it is open,
put following script pretty-json.py in ~/Library/Application\ Support/BBEdit/Text\ Filters/ path
#!/usr/bin/env python
# You can change above she-bang line depending on your Mac configuration
import sys
import json
def main():
input = sys.stdin.read()
try:
obj = json.loads(input)
except Exception as e:
print input + "\n\nERROR: " + str(e)
return 1
print(json.dumps(obj, indent=2))
return 0
if __name__ == '__main__':
sys.exit(main())
To Test, open a JSON file in BBEdit.
Select Text --> Apply Text Filter --> pretty-json.py
If you face any issue like formatting error, then the above script will add error in New file and will not change the original JSON.
which is not the case with this answer
Ref: https://gist.github.com/brokaw/95ade1358954cd97d0f2c8e992e14b08
For more info: Refer this
The above filter works fine for smaller JSON files, but if the JSON file is large(~ 40MB) then formatting will be slow.
To solve this, use the following solution
Solution 2: Using jq
For faster json formatting,
Install jq brew install jq
Check if you are able to execute jq in terminal, or need a full path, add whichever works in following file in place of jq
Add fast-json-pretty.sh file in ~/Library/Application\ Support/BBEdit/Text\ Filters/ location
Restart bbedit.
#!/bin/bash
jq

In BBEdit 14.0 and later, "Reformat Document" on the text menu will reflow JSON. You can also use the built-in Language Server Support with a JSON language server that supports reformatting.

I just corrected this issue in the bundle, for 2.0 users the bundle should update within 24 hours with the correction.

According to http://jsonprettyprint.com/ Textmate and Sublime aren't doing the right thing.
What version of Emacs did you use?
With 24.2.1, your JSON blob indented perfectly without issues in js-mode (Emac's default javascript major-mode).
If you do any significant Javascript development I recommend checkint out js2-mode https://github.com/mooz/js2-mode, which turns Emacs into a great JS IDE.

Sublime Pretty JSON
Sublime Pretty JSON indents the first { well.
This is what I get:
[
{
"settings": [
"master"
],
"appPort": "8666",
"specs": {
"frame": {
"type": "HTMLFrameMojit",
"config": {
"deploy": true,
"child": {
"type": "HelloWorldMojit"
},
"assets": {
"top": {
"css": [
"/static/HelloWorldMojit/assets/index.css"
]
}
}
}
}
}
},
{
"settings": [
"environment:development"
],
"staticHandling": {
"forceUpdate": true
}
}
]
Installation
Within Sublime Text 2: Preference => Package Control => Install Package => "Pretty Json" => Restart Sublime => Select JSON Text => Press:
Linux: ctrl+alt+j
Windows: ctrl+alt+j
OS X: cmd+ctrl+j

This is a solution simply using Google Chrome or NodeJS itself, and here is how:
Just open up the Google Chrome dev tool or NodeJS prompt, and type in
obj =
and copy and paste the object into it, so it will be like
obj = [
{
// etc
Now, in Google Chrome, just type
JSON.stringify(obj, null, 4)
and you will have the formatted JSON. In NodeJS, since it prints out the \n verbatim, you can use
console.log(JSON.stringify(obj, null, 4))
If you want the indentation to be just 2 spaces, just use 2 instead of 4.
If you want the indentation to be tabs instead of spaces, simply use
JSON.stringify(obj, null, "\t")

Create a script file fast-json-pretty.sh in ~/Library/Application\ Support/BBEdit/Text\ Filters/
Insert the following script:
#!/usr/bin/env bash
/usr/local/bin/jq .
Apply the text filter as follows: Menu bar --> Text --> Apply Text Filter --> fast-json-pretty
This is a reworked version of DKB's version of his JQ script as it, at least for me, required the full path and a dot (.) at the end to make this work.

Just check to see which version of python is installed:
using json_pretty will only work if the python interpreter is whatever is installed in the shell being called. For example, my json_pretty works and I have modded it as follows on Ventura:
#!/bin/zsh
python3 -m json.tool

Related

Can we write code snippet for markdown language in Visual Studio Code?

Why markdown language not seems to be supported by code-snippets in vs-code? I've also tried writing "scope: "md" but it also doesn't work.
{
"Print to console": {
"scope": "markdown",
"prefix": "test",
"body": [
"console.log('$1');",
"$2"
],
"description": "description"
}
}
Create some of the other snippet files like html.json.
Save this file with File | Save As... as markdown.json in the same directory.
Fill in your snippet.
In the Markdown file type your snippet prefix and press CtrlSpace and select the snippet you want.
It seems there is not a completion provider that shows the possible completions while you type or it is not enabled by default.

Unexpected end of JSON input in MongoDB Compass

I want to import data of type JSON in MongoDB compass,
the import function gives this error
" unexpected end of JSON input "
there is a some of my JSON file
[
{
"id":4,
"user":"test#example.com",
"date1":"2019-03-01",
"date2":"2019-04-01",
"statut":"Good",
"guest_number":4
}
]
the solution is to write all JSON in one line, but if we have a big doc !!
I just found a solution that I can import data with this command in terminal :
mongoimport --jsonArray --db YourDatabase --collection YourCollection --file Yourfile.json
I had this issue 6 month ago, the solution is write all JSON in one line.
[{"id":4,"user":"test#example.com","date1":"2019-03-01","date2":"2019-04-01","statut":"Good","guest_number":4}]
MongoDB Compass will told you:
Import success!
But definitely the document will not appear in your collection, so better use Robo3T if you gonna insert json. Then you can use again Compass like I do.
It is weird, yes, but I didnt found other solution yet.
[UPDATE]
I achieve import data with Compass, but I achieve exporting first a document from Compass to see how it write the json.
{"_id":{"$oid":"5e4cf105c9ba1a21143d04a2"},"tPreguntas":["Pregunta 1","Pregunta 2","Pregunta 3","Pregunta 4","Pregunta 5"],"tCategorias":[],"tPublico":true,"tFechaCreacion":{"$date":{"$numberLong":"1582100741716"}},"tCodigo":"test1","tTitulo":"Test 1","tDescripcion":"Test de muestreo número uno para comprobar.","tCreadoPor":"eoeo#eoeo.com"}
It look to different to the json online I have post in my first post. (look that objectId "$oid" for example). So if you follow that pattern Compass will import you fine.
This parsing error can be solved using minification. So, minify json like this. Although, it is quite a hectic process to do this for each object.
And this kind of minification like this worked for me.
{
"_id" : ObjectId("5b9ecf9a64f634289ca895bb"),
"name" : "Mark"
}
{
"_id" : ObjectId("5b9edd9064f634289ca895e4"),
"name" : "David"
}
To :
{"_id":"ObjectId(\"5b9ecf9a64f634289ca895bb\")","name":"Mark"}
{"_id":"ObjectId(\"5b9edd9064f634289ca895e4\")","name":"David"}
Just copy the contents of your json file then in Mongodb Compass select your database then click on Add Data which will drop down then click on insert document a dialog pops up then paste it in there and click insert.
This parsing error can be solved using minification. So, minify json like this. Although, it is quite a hectic process to do this for each object.
{
"_id" : "123456",
"name" : "stackoverflow"
}
change to :
{"_id":"123456","name":"stackoverflow"}
This answer here Solution solved the issue for me. It seems to be a formatting issue.
It's an issue with the end-of-line characters (EOL).
In a Windows environment line terminations are normally CR NL (\r\n), while MongoDB Compass seems to only support CR (\r).
You can open the file in Notepad++, enable the "Show all characters" toggle in the toolbar and inspect your current end-of-line character.
To fix the issue, select Edit > EOL Conversion > Macintosh (CR).
The structure of your JSON is incorrect, you might want to read info regarding JSON standards
A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
try using double quotes instead of single ones:
JSON validators could help you aswell
[
{
"id" : 4,
"user" : "test#example.com",
"date1" : "2019-03-01",
"date2" : "2019-04-01",
"statut" : "Good",
"guest_number" : 4
}
]
I had a similar issue but it turned out to be additional line feeds at the end of the file. Removing these fixed the issue. I suggest opening your file in an editor that shows line feeds e.g. Notepad++
Add --jsonFormat=canonical to your mongoexport script:
mongoexport --db=quotes --collection=quotes --jsonFormat=canonical --out=data/quotes.json
JSON can only directly represent a subset of the types supported by BSON. To preserve type information, MongoDB adds the following extensions to the JSON format.
Source
You can also use the command line of mongodb like this :
db.user.insert(
[
{
"id" : 4,
"user" : "test#example.com",
"date1" : "2019-03-01",
"date2" : "2019-04-01",
"statut" : "Good",
"guest_number" : 4
},
{
"id" : 5,
"user" : "test2#example.com",
"date1" : "2019-03-01",
"date2" : "2019-04-01",
"statut" : "Good",
"guest_number" : 4
}
]
Run this command in cmd and the cmd path should be in the same folder where the JSON file occurs.
mongoimport --jsonArray --db YourDatabase --collection YourCollection --file Yourfile.json

export whole Neo4j database / cypher result to GraphJSON

I´ve already had a look at different post like this and this but nothing seems to be answered 100%.
My current problem is, that I want to visualyze - and ideally - analyze my Neo4j-Graph with a library (or software/tool).
The database-server is running on a remote (virtual) server and it seems that there is no chance to export the database to a format where I can work on with.
I´ve tried exporting the graph in a .graphml-file to import this file in Gephi, but Gephi doesn´t find the properties. Gephi-streaming with apoc-procedures and the graph-streaming plugin also does not work, because it´s a remote server (also with the tool mentioned here).
Now I´m currently testing around with Alchemy.js... So far, so good. But as it seems there´s no way to export the graph/query to the GraphJson-format?
Is there really no "easy" way to export the data?
Thanks for your help in advance!
This is how I would proceed
Run this query from the post you mentioned in the Neo4j Browser or in any bolt driver:
MATCH (a)-[r]->(b)
WITH collect(
{
source: id(a),
target: id(b),
caption: type(r)
}
) AS edges
RETURN edges
Now that you have loaded the data, you can simply download it as JSON using download button.(if you are using bolt driver ignore)
Either you manually downloaded JSON from Neo4j Browser or you are using bolt driver, you will end up with something like this.
{
"columns": [
"edges"
],
"data": [
{
"row": [
[
{
"source": 31288,
"target": 152,
"caption": "HAS_PAYMENT_METHOD"
}
]
],
"meta": [
null
],
"graph": {
"nodes": [
],
"relationships": [
]
}
}
]
Now all you have to is to filter out data.row results and you are done. Probably using bolt driver is the better choice as you have to clean up data anyway and it doesnt run into issues with returning a lots of data to the browser(it might crash).
Update: added python version
from neo4j.v1 import GraphDatabase
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "neo4j"))
session = driver.session()
result = session.run("MATCH (a)-[r]->(b) WITH collect({source: id(a),target: id(b),caption: type(r)}) AS edges RETURN edges")
for record in result:
print(record["edges"])
Hope this helps

Activating Material Theme Through Package Control

I've installed the Material Theme through Package Control for Sublime Text. I'm following the install and activation instructions found here: https://packagecontrol.io/packages/Material%20Theme
However, when I get to the Activation part, I can't figure out how to properly insert the JSON code into the (Preferences > Setting - User) file.
I've been copying and pasting the code into the file, but it throws the error:
Error trying to parse settings: Unexpected character, expected a comma or closing bracket in Packages/User/Preferences.sublime-settings:6:1
Any help is appreciated.
{
"ignored_packages":
[
"Vintage"
]
["theme": "Material-Theme.sublime-theme",
"color_scheme": "Packages/Material Theme/schemes/Material-Theme.tmTheme",]
}
Correct answer:
{
"ignored_packages": [
"Vintage"
],
"theme": "Material-Theme.sublime-theme",
"color_scheme": "Packages/Material Theme/schemes/Material-Theme.tmTheme"
}

How to pretty print log output in Chrome DevTools Console?

I'm hoping to be able to pretty print array objects and such in the Console of Chrome DevTools. Is there any means to achieve this?
Thank you!
You could format the data as JSON:
console.log(JSON.stringify({foo:1, bar:2}, null, 4));
{
"foo": 1,
"bar": 2
}
If you are at a breakpoint, you can call JSON.stringify() directly from the Chrome DevTools console:
> JSON.stringify(anObject, null, 2);
<- "{
"field": "foo",
"array": [
{
"element": 1
},
{
"element": 2
}
],
"object": {
"inner_field": "bar"
}
}"
-----------------------------
>
I write some years later and i am older too ... but i found this response trying to pretty print a block of code so i leave tracks of my workarounds.
Now, on december 2020, You can always open js objects in console log clicking on related arrows on the left.
Example:
or you can use as stated before the JSON.stringify() method.
If you whant to pretty print a block of js code minimized in a long line add somewhere at the beginnig of code a debugger statement, than paste to the console and run thwe code.
The Debugger statement will be reached and the code will be opened into "sources" panel. Here you can use the pretty print button. Pay attention, for your security, to put your debugger statement prior of each other executed statement.
Example:
((function(){/*AutoFill_LastPass*/_LPG=function(i){debugger; return document.getElementById(i);};_LPT=function(i){return document.getElementsByTagName(i);};if(_LPG('_lpiframe')){_LPG('_lpiframe').parentNode.removeChild(_LPG('_lpiframe'));}if(_LPG('_LP_RANDIFRAME')){_LPG('_LP_RANDIFRAME').parentNode.removeChild(_LPG('_LP_RANDIFRAME'));}_LASTPASS_INC=function(u,s){if(u.match(/_LASTPASS_RAND/)){alert('Cancelling_request_may_contain_randkey');return;}s=document.createElement('script');s.setAttribute('type','text/javascript');s.setAttribute('src',u);if(typeof(window.attachEvent)!='undefined'){if(_LPT('body').length){_LPT('body').item(0).appendChild(s);}else{_LPT('head').item(0).appendChild(s);}}else{if(_LPT('head').length){_LPT('head').item(0).appendChild(s);}else{_LPT('body').item(0).appendChild(s);}}};_LASTPASS_INC('https://lastpass.com/bml.php'+String.fromCharCode(63)+'v=0&a=0&r='+Math.random()+'&h=456d3ca99bf926f1727a6944fa06db246df102044140c09f0c9922b6ab1fa88a&u='+escape(document.location.href));_LPM=function(m){var targetFrame=_LPG(m.data.frame);if(null!=targetFrame&&typeof(targetFrame)!='undefined'&&typeof(targetFrame.contentWindow)!='undefined')targetFrame.contentWindow.postMessage(m.data,'*');};if(window.addEventListener){window.addEventListener('message',_LPM,false);}else{window.attachEvent('onmessage',_LPM);}var t=document.createElement('iframe');t.setAttribute('id','_LP_RANDIFRAME');t.setAttribute('sandbox','allow-scripts');t.frameBorder='0';t.setAttribute('src','https://lastpass.com/bml.php?u=1&hash=1&gettoken=0&donotcache=1407688374608280546');t.setAttribute('onload',"document.getElementById('_LP_RANDIFRAME').contentWindow.postMessage('ae24188b13eef4ddac2c37d1c449c47156d0a136c7db1d2ca0bd68060bffcc79','*');");if(typeof(window.attachEvent)!='undefined'){if(_LPT('body').length){_LPT('body').item(0).appendChild(t);}else{document.getElementByTagName('head').item(0).appendChild(t);}}else{if(_LPT('head').length){_LPT('head').item(0).appendChild(t);}else{_LPT('body').item(0).appendChild(t);}}})());
Result of running this code in console: