简体   繁体   中英

Parse JSON string to Database

I'm having trouble parsing a JSON string to my MYSQL database. This is the JSON-string sent to the server:

    [{"Description":"Detta är mitt quiz!","Title":"Mitt Quiz","Category":"Music","Language":"Swedish","Difficulty":1},{"QuestionNr1":{"WrongAnswer3":"Visby","WrongAnswer1":"Stockholm","RightAnswer":"Uppsala","WrongAnswer2":"Umeå","Question":"Vilken stad bor jag i?"},"QuestionNr2":{"WrongAnswer3":"Visby","WrongAnswer1":"Stockholm","RightAnswer":"Uppsala","WrongAnswer2":"Umeå","Question":"Vilken stad bor jag inte i?"}}]

This is the data before calling [mArray JSonrepresentation]; on it

(
    {
    Category = Music;
    Description = "Detta \U00e4r mitt quiz!";
    Difficulty = 1;
    Language = Swedish;
    Title = "Mitt Quiz";
},
    {
    QuestionNr1 =         {
        Question = "Vilken stad bor jag i?";
        RightAnswer = Uppsala;
        WrongAnswer1 = Stockholm;
        WrongAnswer2 = "Ume\U00e5";
        WrongAnswer3 = Visby;
    };
    QuestionNr2 =         {
        Question = "Vilken stad bor jag inte i?";
        RightAnswer = Uppsala;
        WrongAnswer1 = Stockholm;
        WrongAnswer2 = "Ume\U00e5";
        WrongAnswer3 = Visby;
    };
}

)

I'm using a POST method of the ASIHTTPRequest but don't know how to receive this on the server side and parse it with PHP to my database.

Can someone point me in the right direction and I would be very happy!

//Thanks!

http://php.net/manual/en/function.json-decode.php

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

loop over $json and build sql query

Unless you're POST ing the JSON-string in a named variable, the contents will be available in the request payload, readable from stdin .

// Read contents from stdin
$json_string = file_get_contents('php://input');

If you're sending the JSON-string as a named POST-variable, it's contents are in $_POST['varname'] .

To parse a JSON-string in PHP, you will use the json_decode function. Parsing success can be checked using the json_last_error function.

// Parse a JSON-string into PHP native equivalents
$json_parsed = json_decode($json_string);

if (json_last_error() === JSON_ERROR_NONE) {
    var_dump($json_parsed);
} else {
    // Error parsing JSON
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM