Contents [hide]
Output
title1 title2
Prerequisites
Prepare input.json with following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "encoding": "UTF-8", "items": [ { "title": "title1", "price": 1080 }, { "title": "title2", "price": 2592 } ] } |
Code examples
JavaScript
1 2 3 4 5 6 7 8 9 | const fs = require( 'fs' ); let file = "./input.json" ; fs.readFile(file, (err, data) => { if (err) throw err; const obj = JSON.parse(data.toString()); for (const item of obj[ "items" ]) { console.log(item[ "title" ]); } }); |
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | use strict; use Data::Dumper; use FileHandle; use File::Basename; use JSON; use utf8; binmode STDOUT, ':utf8' ; my $file = dirname(__FILE__). "/input.json" ; if ( my $fh =new FileHandle( $file )) { local $/ = undef ; my $json_str = < $fh >; $fh -> close (); my $djson = decode_json( $json_str ); foreach my $item (@{ $djson ->{ "items" }}) { print $item ->{ "title" }. "\n" ; } } else { die ( "Failed to open " . $file ); } |
PHP
1 2 3 4 5 6 7 | <?php $file = __DIR__. "/input.json" ; $json_str = file_get_contents ( $file ); $djson = json_decode( $json_str ); foreach ( $djson ->items as $item ){ print ( $item ->title. "\n" ); } |
Python
1 2 3 4 5 6 7 8 9 | import json file = "./input.json" ; fh = open ( file , "r" ) json_str = fh.read() fh.close() djson = json.loads(json_str) for item in djson[ "items" ]: print (item[ "title" ]) |
Ruby
1 2 3 4 5 6 7 8 9 10 11 | require 'json' file = "input.json" json_str = "" File .open(file, "r" ) do |rfh| json_str = rfh.read() end djson = JSON .parse(json_str) for item in djson[ "items" ] print(item[ "title" ]+ "\n" ) end |

Author: Hajime Kurita, CEO/CTO of 1st Class, inc. Search Engineer & Web master
Certificate: AWS SOL Architect, Professional Scrum Master I, Class I IT Engineer(JP national certificate), TOEIC900+, Graduate of Tokyo university
Please follow My English twitter account for updates
IT Relatd service: VPS Ranking