json的初步学习

<!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning /> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL /> <w:BalanceSingleByteDoubleByteWidth /> <w:DoNotLeaveBackslashAlone /> <w:ULTrailSpace /> <w:DoNotExpandShiftReturn /> <w:AdjustLineHeightInTable /> <w:BreakWrappedTables /> <w:SnapToGridInCell /> <w:WrapTextWithPunct /> <w:UseAsianBreakRules /> <w:DontGrowAutofit /> <w:UseFELayout /> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!-- [if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><!-- [if gte mso 10]> <mce:style><! /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --> <!--[endif] --><!-- [if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1026" /> </xml><![endif]--><!-- [if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1" /> </o:shapelayout></xml><![endif]-->

Json’ 是一种数据交互格式之一,客户端和服务端之间的数据交互,

Jsonjsjs 的子集, js 可以很好的解析这种数据格式

Phpjson 的解析主要是基于两个函数: json-encode json_decode

一、json_encode()

有点像mysql 里面的序列化函数,serialize

该函数主要用来将数组和对象,转换为json 格式。先看一个数组转换的例子:

1. 


$arr=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
2.echojson_encode($arr);

结果为1.{"a":1,"b":2,"c":3,"d":4,"e":5}


再看一个对象转换的例子:

1.$obj->body='anotherpost'; 
2. $obj->id=21; 
3. $obj->approved=true; 
4. $obj->favorite_count=1; 
5.$obj->status=NULL; 
6. echojson_encode($obj);

结果

1.{ 
2."body":"anotherpost", 
3."id":21, 
4. "approved":true, 
5. "favorite_count":1, 
6. "status":null 
7.}

由于json
只接受utf-8
编码的字符,所以json_encode()
的参数必须是utf-8
编码,否则会得到空字符或者null
。当中文使用GB2312
编码,
或者外文使用ISO-8859-1 编码的时候,这一点要特别注意。

四、json_decode()

类似与反序列化函数

该函数用于将json 文本转换为相应的PHP 数据结构。下面是一个例子:

通常情况下,json_decode() 总是返回一个PHP 对象,而不是数组。比如:

1. $json='{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
2 var_dump(json_decode($json));

结果就是生成一个PHP 对象:

1.object(stdClass)#1(5){ 
2. ["a"]=>int(1) 
3.["b"]=>int(2) 
4. ["c"]=>int(3) 
5. ["d"]=>int(4) 
6.["e"]=>int(5) 
7. } 

如果想要强制生成PHP关联数组,json_decode()需要加一个参数true:

  $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

  var_dump(json_decode($json),true);

结果就生成了一个关联数组:

  array(5) {

     ["a"] => int(1)
     ["b"] => int(2)
     ["c"] => int(3)
     ["d"] => int(4)
     ["e"] => int(5)

  }

区块链是一种去中心化的分布式账本技术,它可以用于记录交易、资产、身份验证等信息。在Ubuntu 20.04上学习区块链,可以按照以下步骤进行: 1.安装必要的软件包和依赖项 ```shell sudo apt-get update sudo apt-get install build-essential libssl-dev libffi-dev python3-dev ``` 2.安装Python虚拟环境 ```shell sudo apt-get install python3-venv ``` 3.创建并激活Python虚拟环境 ```shell python3 -m venv blockchain-env source blockchain-env/bin/activate ``` 4.安装区块链相关的Python库 ```shell pip install Flask==1.1.2 requests==2.24.0 ``` 5.创建一个简单的区块链 ```python # blockchain.py import hashlib import json from time import time from uuid import uuid4 from flask import Flask, jsonify, request class Blockchain: def __init__(self): self.chain = [] self.current_transactions = [] # Create the genesis block self.new_block(previous_hash='1', proof=100) def new_block(self, proof, previous_hash=None): """ Create a new Block in the Blockchain :param proof: <int> The proof given by the Proof of Work algorithm :param previous_hash: (Optional) <str> Hash of previous Block :return: <dict> New Block """ block = { 'index': len(self.chain) + 1, 'timestamp': time(), 'transactions': self.current_transactions, 'proof': proof, 'previous_hash': previous_hash or self.hash(self.chain[-1]), } # Reset the current list of transactions self.current_transactions = [] self.chain.append(block) return block def new_transaction(self, sender, recipient, amount): """ Creates a new transaction to go into the next mined Block :param sender: <str> Address of the Sender :param recipient: <str> Address of the Recipient :param amount: <int> Amount :return: <int> The index of the Block that will hold this transaction """ self.current_transactions.append({ 'sender': sender, 'recipient': recipient, 'amount': amount, }) return self.last_block['index'] + 1 @staticmethod def hash(block): """ Creates a SHA-256 hash of a Block :param block: <dict> Block :return: <str> """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string).hexdigest() @property def last_block(self): return self.chain[-1] def proof_of_work(self, last_proof): """ Simple Proof of Work Algorithm: - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' - p is the previous proof, and p' is the new proof :param last_proof: <int> :return: <int> """ proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 return proof @staticmethod def valid_proof(last_proof, proof): """ Validates the Proof: Does hash(last_proof, proof) contain 4 leading zeroes? :param last_proof: <int> Previous Proof :param proof: <int> Current Proof :return: <bool> True if correct, False if not. """ guess = f'{last_proof}{proof}'.encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == "0000" # Instantiate our Node app = Flask(__name__) # Generate a globally unique address for this node node_identifier = str(uuid4()).replace('-', '') # Instantiate the Blockchain blockchain = Blockchain() @app.route('/mine', methods=['GET']) def mine(): # We run the proof of work algorithm to get the next proof... last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) # We must receive a reward for finding the proof. # The sender is "0" to signify that this node has mined a new coin. blockchain.new_transaction( sender="0", recipient=node_identifier, amount=1, ) # Forge the new Block by adding it to the chain previous_hash = blockchain.hash(last_block) block = blockchain.new_block(proof, previous_hash) response = { 'message': "New Block Forged", 'index': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'], } return jsonify(response), 200 @app.route('/transactions/new', methods=['POST']) def new_transaction(): values = request.get_json() # Check that the required fields are in the POST'ed data required = ['sender', 'recipient', 'amount'] if not all(k in values for k in required): return 'Missing values', 400 # Create a new Transaction index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount']) response = {'message': f'Transaction will be added to Block {index}'} return jsonify(response), 201 @app.route('/chain', methods=['GET']) def full_chain(): response = { 'chain': blockchain.chain, 'length': len(blockchain.chain), } return jsonify(response), 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) ``` 6.运行区块链应用程序 ```shell export FLASK_APP=blockchain.py flask run --port 5000 ``` 现在,您可以使用Postman或类似的工具向http://localhost:5000/transactions/new发送POST请求来创建新的交易,向http://localhost:5000/mine发送GET请求来挖掘新的区块,并向http://localhost:5000/chain发送GET请求来获取整个区块链。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值