JSON: Difference between revisions

2,315 bytes added ,  9 years ago
Added Prolog solution
(Added Prolog solution)
Line 2,197:
12:25:25 PM 1414326325923 10-26-2014
</lang>
 
=={{header|Prolog}}==
 
Using SWI-Prolog 7's library(http/json), and the new dict datatype, there is nearly transparent handling of JSON objects. All of the serialization and parsing in the following code is accomplished with two predicates. The rest of the code is for the sake of example.
 
<lang Prolog>:- use_module([ library(http/json),
library(func) ]).
 
test_json('{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" }}}').
 
reading_JSON_term :-
atom_json_dict(test_json(~), Dict, []), %% This accomplishes reading in the JSON data
writeln( 'JSON as Prolog dict: ~w~n'
$ Dict),
writeln( 'Access field "widget.text.data": ~s~n'
$ Dict.widget.text.data),
writeln( 'Alter field "widget": ~w~n'
$ Dict.put(widget, "Altered")).
 
searalize_a_JSON_term :-
Dict = _{book:_{title:"To Mock a Mocking Bird",
author:_{first_name:"Ramond",
last_name:"Smullyan"},
publisher:"Alfred A. Knopf",
year:1985
}},
json_write(current_output, Dict). %% This accomplishes serializing the JSON object.</lang>
 
Output from these two example predicates:
 
<lang Prolog>?- reading_JSON_term.
JSON as Prolog dict: _G5217{widget:_G5207{debug:on,image:_G5123{alignment:center,hOffset:250,name:sun1,src:Images/Sun.png,vOffset:250},text:_G5189{alignment:center,data:Click Here,hOffset:250,name:text1,onMouseUp:sun1.opacity = (sun1.opacity / 100) * 90;,size:36,style:bold,vOffset:100},window:_G5077{height:500,name:main_window,title:Sample Konfabulator Widget,width:500}}}
 
Access field "widget.text.data": Click Here
 
Alter field "widget": _G5217{widget:Altered}
 
true.
 
?- searalize_a_JSON_term.
{
"book": {
"author": {"first_name":"Ramond", "last_name":"Smullyan"},
"publisher":"Alfred A. Knopf",
"title":"To Mock a Mocking Bird",
"year":1985
}
}
true.</lang>
 
=={{header|Python}}==