0

I have sth like that inside *.txt file.

function_name({"one": {"id": "id_for_one", "value": "value_for_one"}, ...});

And I am getting the file like this:

$source = 'FILE_NAME.txt';
$json = json_decode(file_get_contents($source),true);
echo $json['one']['value'];

It doesn't work, but when I remove function_name( and ); it works. How to parse it without removing these strings?

3
  • what are you trying to achieve? Commented Feb 20, 2012 at 21:20
  • That should be a JS callback function. Commented Feb 20, 2012 at 21:21
  • The hells are you doing? json_decode() is meant for decoding a JSON string. The string you are giving it is not a JSON string. Commented Feb 20, 2012 at 21:28

5 Answers 5

1

You can't. It is not valid JSON with those. Take a substring that excludes them.

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

Comments

1

You will have to remove those strings. With the function_name portion it is not valid JSON.

A JSON string will typically either begin with { (object notation) or [ (array notation), but can also be scalar values such as a string or number. You cannot parse it without first making sure the string is valid JSON.

1 Comment

JSON does not have to be enclosed in an object or array.
1

You are trying to get the string within a file and decoding it as a JSON file.

The 'function_name' isn't a valid JSON string, the rest inside yes.

Comments

1

How to parse it without removing these strings?

There is no way.
This should work for you.

$data = file_get_contents($source);
$data = substr($data, strlen("function_name("));
$data{strlen($data)-1}=$data{strlen($data)-2}=" ";
$json = json_decode($data,true);

Both {} and [] works for string to access individual characters.

Comments

0

The function in your text file, means that isn't a json file.

Remove the string using a regular expression, and your problem is fixed.

If the function is a fixed name, do something like this:

$source = 'FILE_NAME.txt';
$json_content = str_replace('function_name(', '', file_get_contents($source));
$json_content = substr($json_content,0,-2);
$json = json_decode($json_content,true);
echo $json['one']['value'];

2 Comments

What if the function_name appears in JSON as well?
if is inside the JSON, then will become an string. Or will invalidate your object and if is invalid, isn't a JSON too. Take a look in this article json.org

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.