ML Blog

雕刻时光
Sculpting in time

Do one thing and do it well.
Every story has a beginning and an end.

2-Minute Read

Today, in the course of work, I need to parse a JSON file to get a keyword, and I’m going to use Mathematica to practice.

``` `` { “apiVersion”: “v1”, “data”: { “voting-keystore.json”: “{ "version": 4, "pubkey": " a94300da6d73a11d8ba72c99dd385b7a9d5043c9ee83ffd4190d89b7677e68d384fbceb556d2a0652e81250ad4b8477d", ""uuid”: "09e5c322-bf6b-401a -b90d-1aef6d57996a", "crypto": {"checksum": {"message": "704e947d244bc8020ef6d6f0844c4aea08af18ecf345bb98ab999df6441377d7\ "function": "sha256", "params": {}}, "kdf": {"message": """, "function": "scrypt", "params": {"p": 1, "n": 32768, "salt": "b891518a06f1d3f67a6d485bba8627f5320497f98c08cb52e4391e50071ac97d", "dklen": 32, "r": 8}}, "cipher": {\" message": "bcd85ce03e82e645e135e13501f717d907c03a23ee1f8dc6bd045c53001719ddc7a5\", "function": "aes-128-ctr", "paragraphs": {"iv\ “: "7f05ffce95bcd0157e520c6b949b90b1"}}}, "path": """}”" }, “kind”: “ConfigMap”, “metadata”: { “creationTimestamp”: “2020-07-25T11:35:24Z”, “managedFields”: [ { “apiVersion”: “v1”, “fieldsType”: “FieldsV1”, “ffieldsV1”: { “f:data”: { “.” : {}, “f:voting-keystore.json”: {} } }, “manager”: “Swagger-Codegen”, “operation”: “Update”, “time”: “2020-07-25T11:35:24Z” } ], “name”: “lighthouse-validator-a94300da6d73”, “namespace”: “eth”, “resourceVersion”: “1200502”, “selfLink”: “/api/v1/namespaces/eth/configmaps/lighthouse-validator-a94300da6d73”, “uid”: “05b37640-be81-4944-9c9f-868431b6107f” } }


One line using wolfram:

The code uses Mathematica's core guidelines, Rule Rules **/. **/.

Rule(->)

For example, {x, x^2, a, b} /. x -> 3 we get: {3, 9, a, b}

(* writeKey["/tmp/json.file", “/tmp/1.txt”] *)

writeKey[srcfile_String, destfile_String] := With[{openfile = File[destfile]}, WriteString[openfile, “pubkey” /. ImportString[ “voting-keystore.json” /. (“data” /. Import[srcfile, “JSON”]), “JSON”]]]


Suppose we have a bunch of json files, and we need to parse the keywords in them and store them in a file, we can do the same with one line of code.

writeKey[#, “/tmp/keys.txt”] & /@ FileNames[All, “/tmp/keys”]; ``

When we talk about a language, we talk about its features, advantages and disadvantages, but I just want to say that the language that brings productivity is the one worth talking about. Worse is much better than a language that does not improve efficiency, and Wolfram Language is one such language.

Recent Posts

Categories

About

不断的学习思考, 保持好奇心
Keep thinking, Stay curious
始终保持对于新事物的敏感
Always be sensitive to new things