2

I tried to parse JSON object with PHP in bash.

{
    "department": {
        "name": "MyDepartment",
        "emp_no": 10
    }
}

And

#!/bin/sh
key=department->name
jsonbody=./object.json

value=$(php -r "\$obj = json_decode(utf8_encode(file_get_contents('$jsonbody')));print \$obj->'$key';")

I got the error message as below. How can handle JSON object with bash variable?

PHP Parse error:  syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or '{' or '$' in Command line code on line 1

1 Answer 1

1

This solves it:

#!/bin/sh
key='department->name' # or key="department->name"
jsonbody=./object.json

value=$(php -r "\$obj = json_decode(utf8_encode(file_get_contents('$jsonbody')));print \$obj->$key;")
# $key, not '$key'

echo $value
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.