Troubleshooting JSON parsing issues in PHP

In reference to the discussion at: , where suggestions mainly revolved around JavaScript.

Is there a specific function in PHP that can be utilized to address the issue described below and ensure that the output is valid JSON? Please note that using front end (JS) solutions is not feasible in this scenario. The problem seems to stem from the unquoted number leading into the array. Unfortunately, fixing the source directly is not an option for me.

 {
    29646191: [
        "https://www.facebook.com/RobertScoble/posts/480030845352725",
        "https://sphotos-a.xx.fbcdn.net/hphotos-prn1/s480x480/546943_10151235934049655_1771118951_n.jpg",
        "Today I tried... | Facebook",
        "Robert Scoble wrote: Today I tried something. I paid $49 and... Join Facebook to connect with Robert Scoble and others you may know.",
        null,
        [
            "//images3-focus-opensocial.googleusercontent.com/gadgets/proxy?url\u003dhttps://sphotos-a.xx.fbcdn.net/hphotos-prn1/s480x480/546943_10151235934049655_1771118951_n.jpg\u0026container\u003dfocus\u0026gadget\u003da\u0026rewriteMime\u003dimage/*\u0026refresh\u003d31536000\u0026resize_h\u003d150\u0026resize_w\u003d150\u0026no_expand\u003d1",
            150,
            150,
            null,
            null,
            null,
            null,
            null,
            [
                3,
                "https://images1-focus-opensocial.googleusercontent.com/gadgets/proxy?url\u003dhttps://sphotos-a.xx.fbcdn.net/hphotos-prn1/s480x480/546943_10151235934049655_1771118951_n.jpg\u0026container\u003dfocus\u0026gadget\u003dhttps://plus.google.com\u0026rewriteMime\u003dimage/*\u0026resize_h\u003d800\u0026resize_w\u003d800\u0026no_expand\u003d1"
            ]
        ],
        "//s2.googleusercontent.com/s2/favicons?domain\u003dwww.facebook.com",
        [],
        null,
        []
    ]
}

Edit: Basic functions like json encode/decode do not seem to work here. It appears that the data has undergone multiple transformations before it can even be processed by PHP.

To clarify, the following snippet illustrates the preprocessing steps that occur prior to dealing with the mentioned issue:

       $instring = false;
    $inescape = false;
    $lastchar = '';
    $output = "";
    for ( $x=0; $x<strlen( $sourcejson ); $x++ ) {

        $char = substr( $sourcejson, $x, 1 );

        //toss unnecessary whitespace
        if ( !$instring && ( preg_match( '/\s/', $char ) ) ) {
            continue;
        }

        //handle strings
        if ( $instring ) {
            if ( $inescape ) {
                $output .= $char;
                $inescape = false;
            } else if ( $char == '\\' ) {
                $output .= $char;
                $inescape = true;
            } else if ( $char == '"' ) {
                $output .= $char;
                $instring = false;
            } else {
                $output .= $char;
            }
            $lastchar = $char;
            continue;
        }


        switch ( $char ) {

            case '"':
                $output .= $char;
                $instring = true;
                break;

            case ',':
                if ( $lastchar == ',' || $lastchar == '[' || $lastchar == '{' ) { 
                    $output .= 'null';
                }
                $output .= $char;
                break;

            case ']':
            case '}':
                if ( $lastchar == ',' ) { 
                    $output .= 'null';
                }
                $output .= $char;
                break;

            default:
                $output .= $char;
                break;
        }
        $lastchar = $char;
    }

Answer №1

Avoid attempting to manually encode or decode JSON.

To encode JSON from a PHP array:

echo json_encode($data);

To decode JSON:

var_dump(json_decode($data));

In your specific situation, you must convert the integer to a string. Here is a solution:

# this method requires PHP >= 5.4.0
var_dump(json_decode($data, false, 512, JSON_BIGINT_AS_STRING));

Refer to json_decode() for further details


UPDATE

If the previous steps are unsuccessful, I recommend ensuring that valid JSON is sent from JavaScript before processing it with your PHP script.

// unfortunately, this seems to be the only viable solution; fortunately, the JSON comes from a trustworthy source (Google), so eval shouldn't pose a threat;
jsonObject = eval('(' + invalidJsonString + ')');

// convert the object back to a JSON string
validJsonString = JSON.stringify(jsonObject);

// hooray, now we have valid JSON
console.log(validJsonString);

View it in action on jsfiddle

Disclaimer

Typically, you would use jQuery.parseJSON(jsonString) or JSON.parse(jsonString), but these options result in a parsing error when an integer is used as a key in the object :(

Answer №2

If you want to decode JSON in PHP, make sure to utilize the json_decode(); function.

Give this code a try:

$jsonData[] = //json data;
 var_dump(json_decode($jsonData));

Then, you can use the following code to check for any errors:

json_last_error()

For more information, refer to the official documentation: http://www.php.net/manual/en/function.json-decode.php

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for dynamically assigning a color picker hex value as HTML attributes in PHP?

Is it possible to create a color picker that allows the user to select a hex value and then automatically apply it as an attribute in an HTML tag, like shown below? <p style="background-color: #FCF8C0;">TEXT GOES HERE</p> In the code example ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

Search for a substring in JSON using Python

Currently, I am faced with the challenge of extracting two pieces of information from a lengthy JSON file using Python 2.7. The structure of the JSON data is as follows: { 'device': [ { 'serial': '00000000762c1d3c&apo ...

consolidating various data into a single field

In order to personalize the user experience, I aim to provide individuals with the ability to choose their academic majors. For instance, a student named Person A may opt for computer science, mathematics, and history as their chosen fields of study. User ...

Is there a way to dynamically fetch and run JavaScript code from the server without resorting to the use of the

In my current project, I am developing a unique PHP framework that empowers PHP developers to effortlessly craft ExtJS interfaces containing forms, grids, tabpanels, and menus exclusively through PHP classes. To illustrate, creating a TabPanel in this fra ...

No changes occur when running the command composer.phar update

Whenever I input the line below into the terminal, nothing occurs: php composer.phar update The same outcome happens with install or any other option. Any ideas on what might be causing this issue? My operating system is CentOS. Thank you ...

PHP's json_encode() compared to using an empty NSDictionary in iOS development

I have a question regarding how to handle JSON encoding/decoding in PHP without converting arrays or dictionaries. In my iOS app, I store data in an NSDictionary. Some of this data is nested and includes NSArrays or other NSDictionarys that may contain fu ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...

Input form and select form collide in conflict when the "Enter" key is activated

My search box includes input forms and a select form with various options. The issue arises when using the place autocomplete feature from Google Maps alongside the select form. When the enter key is pressed after entering a location in the autocomplete fi ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

Mobile compatibility in ECMAScript 5.1 is essential for creating seamless user

Is there a reliable source for information on ECMAScript 5.1 compatibility with mobile browser devices? ...

Unraveling the complexities of double-encoded UTF-8 in PHP

Trying to transmit data from an HTML page via Ajax to a PHP page. This is the jQuery code I'm using: $.ajax({ url: "test.php", type: "POST", data: { name: "João" } }).done(function (data) { alert(data); }) When sending ...

A guide on tallying the frequency of a word's appearance on a website using PHP

Is there a way to create a PHP script that can count how many times a specific word appears on a webpage? I have the following code snippet, is this the right approach: <?php $url="watever.com"; the script here echo(result); ?> I currently have a s ...

What is the best way to transform the data stored in Observable<any> into a string using typescript?

Hey there, I'm just starting out with Angular and TypeScript. I want to get the value of an Observable as a string. How can this be achieved? The BmxComponent file export class BmxComponent { asyncString = this.httpService.getDataBmx(); curr ...

When you open the responsive navigation bar, it automatically closes

After creating a website some time ago, I decided to make it responsive by adding a menu. However, I encountered an issue where the menu bar opens but immediately closes after showing the entire list. Here is the HTML code for the menu: <!-- start men ...

How to use jQuery to update a text input field based on a selected <select> dropdown option

Hi there, I could really use some help with this issue... Here's the problem - I need to change the value of a textbox within a table based on the selection of an option in a dropdown. Here's a simplified version of what I mean: <select id= ...

Fixing a menu hover appearance

I recently encountered a small issue with the menu on my website. When hovering over a menu item, a sub-menu should appear. However, there seems to be a slight misalignment where the submenu appears a few pixels below the actual menu item. Check out the w ...

Navigating data within a JSON file with D3 javascript: a step-by-step guide

Currently, I am attempting to extract and manipulate data from a JSON file using D3 Javascript. Below is the content of the JSON file: { "Resources": [ { "subject": "Node 1", "group" : "1" }, { "predicate": ...

Tips for converting a string to RAW data type in Oracle using PHP

Currently struggling with sending lengthy strings to Oracle stored procedure RAW variable, encountering the following error: oci_execute(): ORA-06502: PL/SQL: numeric or value error In need of assistance on converting a String to Raw datatype. ...

Generating HTML within controller actions

I am struggling to make a decision on whether it is acceptable to generate HTML in controller actions and return this HTML to AJAX calls from my view using jQuery. For example, when choosing a client through jQuery Autocomplete, in addition to retrieving ...