如何获取JSON中的键值?

时间:2019-05-31 18:34:29

标签: json regex linux bash grep

我有一个JSON正文。我想获取“ access_token”的值。我想在bash中使用grep。我使用的grep无法正常工作。

我尝试了以下操作,但结果空白。

HTTP_BODY=$(echo $HTTP_RESPONSE | grep ^"access_token":" ","experies_in$ )

我只想获取access_token值,即:

eyJhbGciOiJSUzI1NiIsImtpZCI6IkE4M0UwQTFEQTY1MzE0NkZENUQxOTFDMzRDNTQ0RDJDODYyMzMzMzkiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJxRDRLSGFaVEZHX1YwWkhEVEZSTkxJWWpNemsifQ.eyJuYmYiOjE1NTkzMTYzNTYsImV4cCI6MTU1OTMxOTk1NiwiaXNzIjoiaHR0cHM6Ly9jaW5jaHktbnByLmNsb3VkLnJlcy5ibmdmLmxvY2FsL2NpbmNoeXNzbyIsImF1ZCI6WyJodHRwczovL2NpbmNoeS1ucHIuY2xvdWQucmVzLmJuZ2YubG9jYWwvY2luY2h5c3NvL3Jlc291cmNlcyIsImpzX2FwaSJdLCJjbGllbnRfaWQiOiJhcGkiLCJzdWIiOiIxIiwiYXV0aF90aW1lIjoxNTU5MzE2MzU2LCJpZHAiOiJsb2NhbCIsInByb2ZpbGUiOiJBZG1pbmlzdHJhdG9yIiwiZW1haWwiOiJhZG1pbkBjaW5jaHkuY28iLCJyb2xlIjoiQ2luY2h5IFVzZXIgQWNjb3VudCIsImlkIjoiYWRtaW4iLCJzY29wZSI6WyJqc19hcGkiXSwiYW1yIjpbImN1c3RvbSJdfQ.O0--cahxPKlwHp-7fP0CMgSJTaXleupH32x7vVoxe8THVdeRIgyuZoKWPAK9p10PMO9a5Mi3N0t1Nqut5-dUS7lmeUfNKe25K1got9de7ghQ56QQXnL2SWd6g4I8Zi1R9fZsln7bZCIJvnG3_wIWHKGHBco9jEvKtO3AdYF4T9LAbdpT51SDzKPhX16BPc0Do6KfNImQpPQdK4fP3-JqxD4sOBldUg-g3aau2F_DmapEd0p5hTI4qeKgORnXJ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