读取Json文件并解析

Contents

输出结果

title1
title2


先决条件

Prepare input.json with following content.

{
    "encoding": "UTF-8",
    "items": [
        {
            "title": "title1",
            "price": 1080
        },
        {
            "title": "title2",
            "price": 2592
        }
    ]
}

程式码


JavaScript

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

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

<?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

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

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