How do I write JSON data to a file?

data is a Python dictionary. It needs to be encoded as JSON before writing. Use this for maximum compatibility (Python 2 and 3): import json with open(‘data.json’, ‘w’) as f: json.dump(data, f) On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using: import json with open(‘data.json’, ‘w’, encoding=’utf-8′) … Read more

How to prettyprint a JSON file?

The json module already implements some basic pretty printing in the dump and dumps functions, with the indent parameter that specifies how many spaces to indent by: >>> import json >>> >>> your_json = ‘[“foo”, {“bar”:[“baz”, null, 1.0, 2]}]’ >>> parsed = json.loads(your_json) >>> print(json.dumps(parsed, indent=4, sort_keys=True)) [ “foo”, { “bar”: [ “baz”, null, 1.0, … Read more

Convert form data to JavaScript object with jQuery

serializeArray already does exactly that. You just need to massage the data into your required format: function objectifyForm(formArray) { //serialize data function var returnArray = {}; for (var i = 0; i < formArray.length; i++){ returnArray[formArray[i][‘name’]] = formArray[i][‘value’]; } return returnArray; } Watch out for hidden fields which have the same name as real inputs … Read more

Parse JSON in JavaScript? [duplicate]

The standard way to parse JSON in JavaScript is JSON.parse() The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple: const json = ‘{ “fruit”: “pineapple”, “fingers”: 10 }’; const obj = JSON.parse(json); console.log(obj.fruit, obj.fingers); The only time you … Read more

How do I format a Microsoft JSON date?

eval() is not necessary. This will work fine: var date = new Date(parseInt(jsonDate.substr(6))); The substr() function takes out the /Date( part, and the parseInt() function gets the integer and ignores the )/ at the end. The resulting number is passed into the Date constructor. I have intentionally left out the radix (the 2nd argument to … Read more

pretty-print JSON using JavaScript

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use: var str = JSON.stringify(obj, null, 2); // spacing level = 2 If you need syntax highlighting, you might use some regex magic like so: function syntaxHighlight(json) { if (typeof json != ‘string’) { json = JSON.stringify(json, undefined, … Read more

How do I POST JSON data with cURL?

You need to set your content-type to application/json. But -d (or –data) sends the Content-Type application/x-www-form-urlencoded, which is not accepted on Spring’s side. Looking at the curl man page, I think you can use -H (or –header): -H “Content-Type: application/json” Full example: curl –header “Content-Type: application/json” \ –request POST \ –data ‘{“username”:”xyz”,”password”:”xyz”}’ \ http://localhost:3000/api/login (-H … Read more

tech