Friday, 21 December 2018

Saving data to json with python

Wabaluba dub dub it's free-code Friday!
Sometimes you sit down on nice chill weekend and think to yourself, oh boy I want to store some data!

But in all seriousness, let's say you want to run something this evening and return to it tomorrow. Or perhaps you would like to retrieve data from a previous Maya session that crashed, or from a different Maya session entirely - You can save this data out to a separate file (essentially a big text file) called a Json.
Json's are nice to use because they're easy to read/edit and easy to implement into your code. Here's some example code of how to use them below!

import json

# Create some data
data = {1 : 'a', 2 : 'b', 3 : 'c'}

filePath = "C:/User/Documents/test_data.json"

# Write/Export from variable to text file

with open(filePath, 'w') as f:

  json.dump(data, f, indent=4)

# Read/Load from text file to variable

with open(filePath, 'r') as fp:

    data = json.load(fp)

# Read/Load from dictionary text file to ORDERED dictionary

with open(filePath, 'r') as fp:

    data = json.load(fp, object_pairs_hook=collections.OrderedDict)

No comments:

Post a comment